2016-11-05 89 views
0

後運行命令我使用JSch運行多層次的ssh後的一些命令:JSch:多層次的ssh

public static void main(String[] args) { 

    String user="User0"; 
    String ip="IP0"; 
    int port=22; 
    String password="Password0"; 
      JSch jsch= new JSch(); 
      Session session=null; 
      ChannelExec channel=null; 
      try { 
       session=(jsch.getSession(user, ip, port)); 
       session.setConfig("StrictHostKeyChecking", "no"); 
       session.setPassword(password); 
       session.connect(); 
       String dir=Reomte_DIR; 
       String cmd1=SomeComplexCommand; 
       String cmd2=SomeMoreComplexCommand; 
       channel = (ChannelExec) session.openChannel("exec"); 
       channel.setInputStream(null); 
       channel.setCommand("ssh [email protected]_PasswordLessLogin;ssh [email protected]_PasswordLessLogin; "+cmd1+" ; "+cmd2+" ;"); 
       channel.setPty(true); 
       channel.connect(4000); 
       String res = null; 
        BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream())); 
        BufferedReader error = new BufferedReader(new InputStreamReader(channel.getErrStream())); 
        if ((res = error.readLine()) == null) { 
         res = input.readLine()+input.readLine()+input.readLine()+input.readLine(); 
        } else { 

         res = "-1"; 
        } 
       System.out.println("result:"+res); 

      } catch (JSchException e) { 
       e.printStackTrace(); 
      }catch (IOException e) { 
       e.printStackTrace(); 
      }finally { 
       channel.disconnect(); 
       session.disconnect(); 
      }  
     } 

,但它不會給期望的結果。

Infact channel.getInputStream()掛起。如果我刪除多級別的SSH,一切工作正常! 我做錯了什麼?

我得到了一些提示:Multi-level SSH login in JavaMultiple commands using JSch但我無法讓我的代碼運行。

+0

你的命令是錯誤的,你是否先在命令行嘗試它? –

回答

0

你的命令是錯誤的。

您的命令將執行第一個命令ssh [email protected]_PasswordLessLogin

然後它會在執行第二個命令之前等待它完成。

  • 第一個ssh命令永遠不會結束,因爲它將永遠持續等待用戶輸入命令。
  • 即使第一個ssh完成,第二個ssh將在初始主機上執行,而不是一個IP1

你需要的東西是這樣的:

ssh [email protected]_PasswordLessLogin ssh [email protected]_PasswordLessLogin "<cmd1> ; <cmd2>" 

這告訴第一ssh執行對IP1第二ssh;和第二個sshIP2上執行<cmd1> ; <cmd2>

+0

它工作。謝謝!! –