2014-09-10 66 views
0

我想用jsch連接到遠程交換機並運行一些命令並提取輸出。Jsch:命令輸出不可用

我能夠使用連接到交換機,但命令輸出在輸入流中不可用。也許我沒有按照正確的方式去做。這裏的代碼

session = jsch.getSession("user", "10.0.0.0", 22); 
    session.setPassword("somepwd"); 
    session.setConfig("StrictHostKeyChecking", "no"); 
    session.connect(); 
    System.out.println("connected to remote host"); 
    Channel channel = session.openChannel("shell"); 

    OutputStream ops = channel.getOutputStream(); 
    PrintStream ps = new PrintStream(ops); 
     channel.connect(); 
      ps.println("show version"); 
      ps.flush(); 
      ps.close(); 
      InputStream in=channel.getInputStream(); 
      byte[] bt=new byte[1024]; 


      while(in.available()>0) 
      { 
       int i=in.read(bt, 0, 1024); 
       if(i<0) 
       break; 
        String str=new String(bt, 0, i); 
       //displays the output of the command executed. 
        System.out.print(str); 
      } 

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

當我調試inputStream.isAvailable()總是返回零暗示沒有輸出命令。

TIA!

+0

http://www.jcraft.com/jsch/examples/Shell.java.html – 2014-09-10 10:17:44

+0

當您的代碼達到'while(in.available()> 0)時會發生什麼?它掛起來還是別的東西? – Kenster 2014-09-12 13:25:05

+0

它不掛..總是假的條件.. – ayush 2014-09-15 07:35:27

回答

3

請嘗試下面的代碼 - 測試和工作

Channel channel = session.openChannel("shell"); 
    OutputStream ops = channel.getOutputStream(); 
    PrintStream ps = new PrintStream(ops); 
    channel.connect(); 
    ps.println("pwd"); 
    ps.println("exit"); 
    ps.flush(); 
    ps.close(); 

    InputStream in = channel.getInputStream(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
    System.out.println("Opening..."); 

    String jarOutput; 
    while ((jarOutput = reader.readLine()) != null) 
     System.out.println(jarOutput); 
    reader.close(); 
    channel.disconnect(); 

輸出 -

開幕...
用戶@主持人:〜> PWD
/home/user中
用戶@host:〜>
user @ host:〜> exit
註銷

+0

好的一塊代碼毗溼奴。如果我想執行ps.println(「sudo -u myuser -i」); ps.println( 「MYPASSWORD」);這是一個無限的等待/掛起。如何處理這個? – aiman 2017-12-21 13:48:20

+0

sudo -u myuser -i,我必須替換實際的用戶權限? 一旦我嘗試過,我會盡快回復您。 – 2017-12-28 06:12:26