2016-11-05 34 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

它工作。谢谢!! –