jsch

2012-02-29 7 views
0

を使用してssh経由でDiginetデバイスに接続したときのpythonスクリプトの出力を取得するjschのChannelExecを使用してDigi Transport WR21ルータに接続していますが、コマンドを実行すると「modemstat?私は結果をキャプチャすることができますが、Pythonスクリプトを実行しようとすると、 "python hello.py"と言いますと、 "OK"となり、チャンネルは閉じられてからスクリプトから出力をキャプチャできます。誰もがPythonスクリプトの出力を取得する方法を知っていますか?jsch

コマンドコード:

private void sendCommand(String ipAddress, String aCommand) { 
    JSch jsch = new JSch(); 

    try { 
     Session session = jsch.getSession("username", ipAddress, 22); 
     session.setPassword("password"); 

     java.util.Properties config = new java.util.Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     session.setConfig(config); 

     session.connect(3*1000); 

     Channel channel = session.openChannel("exec"); 
     ((ChannelExec) channel).setCommand(aCommand); 

     channel.setInputStream(System.in); 
     InputStream in = channel.getInputStream(); 

     channel.connect(3*1000);  
     StringBuilder commandOut = new StringBuilder(); 

     byte[] tmp = new byte[1024]; 
     while (true) { 
      while (in.available() > 0) { 
       int i = in.read(tmp, 0, 1024); 
       if (i < 0)break; 
       //System.out.print(new String(tmp, 0, i)); 
       //System.out.println(channel.getInputStream().toString()); 
       commandOut.append(new String(tmp, 0, i)); 

       //setChanged(); 
       //notifyObservers(System.err.toString() + "\n"); 
      } 
      if (channel.isClosed()) { 
       System.out.println("exit-status: " 
       + channel.getExitStatus()); 
       break; 
      } 
      try { 
       Thread.sleep(1000); 
      } catch (Exception ee) { 
       throw new JSchException("Cannot execute remote command: " + aCommand + " : " + ee.getMessage()); 
      } 
     } 

     channel.disconnect(); 
     session.disconnect(); 

     System.out.println(commandOut); 


    } catch (JSchException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

コマンドライン、スクリプトhello.py最初の出力は「OK」から実行した場合、約秒後に、それは出力の「Hello World」を。

+0

シェルから起動した場合、このスクリプトは何かを出力しますか? –

+0

はい。 hello.pyスクリプトは最初に「OK」を出力し、その後約2秒後に「Hello World」を出力します。時間の遅れは、pythonがボックスに実装される方法のためです(スクリプトを処理するためにスレッドをオフにするようです)。 – Ryland

答えて

1

答えは2倍です。 Part 1は、私のコマンドの最後から "\ r \ n"が欠けていたので、 "python hello.py"は "python hello.py \ r \ n"だったはずです。パート2では、ChannelExecの代わりにChannelShellを使用する必要があるということです。

関連する問題