2016-11-05 4 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を実行します。

そして、2番目のコマンドを実行する前に終了するのを待ちます。

  • 最初のsshコマンドは、ユーザがコマンドを入力するのを永久に保つため、終了しません。
  • 最初のsshが完了しても、の2番目のホストは、IP1ではなく、最初のホストで実行されます。

あなたはこのようなものが必要:

これは IP1上の第二 sshを実行するための最初の ssh伝え
ssh [email protected]_PasswordLessLogin ssh [email protected]_PasswordLessLogin "<cmd1> ; <cmd2>" 

。第2のsshIP2<cmd1> ; <cmd2>を実行します。

+0

それは働いた。ありがとう!! –

関連する問題