2013-03-05 34 views
0

我試圖從通過ssh發送的命令獲得響應。我使用JSch庫進行連接。連接已建立,但從發送的命令中得不到迴應。無法從命令獲得響應(使用JSch)

public void openSSH(
     String username, 
     String password, 
     String hostname, 
     int port) throws Exception {  

    JSch jsch = new JSch(); 
    Session session = jsch.getSession(username, hostname, 22); 
    this.session = session; 
    session.setPassword(password); 

    // Avoid asking for key confirmation 
    Properties prop = new Properties(); 
    prop.put("StrictHostKeyChecking", "no"); 
    session.setConfig(prop); 
    session.connect(); 

} 

public String runCommand(String command) throws Exception { 
    // SSH Channel 
    ChannelExec channelssh = (ChannelExec) session.openChannel("exec");  
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    InputStream in = channelssh.getInputStream(); 
    channelssh.setOutputStream(baos); 

    // Execute command 
    channelssh.setCommand(command); 
    channelssh.connect();   



    System.out.println("Unix system connected..."); 
     byte[] tmp = new byte[1024]; 
     while (true){ 

      while (in.available() > 0) { 
       Log.v("running", "line"); // won't work 
       int i = in.read(tmp, 0, 1024); 
       if (i < 0) { 

        break; 
       } 
       String line = new String(tmp, 0, i); 
       System.out.println("Unix system console output: " +line); 
         channelssh.disconnect(); 
      } 
     } 
} 



private class AsyncTaskOne extends AsyncTask<Void, Void, Boolean> { 


    @Override 
    protected Boolean doInBackground(Void... params) { 

     try { 
      openSSH("login", "pass", "10.10.10.80", 22); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     return true; 
    } 

    protected void onPostExecute(Boolean value) { 

     if (value) { 
     try { 
      runCommand("ls -llh"); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     } 
    } 

} 

回答

0

請檢查您的InputStream爲可用actually.From我的理解,問題是你的inputStream沒有按;噸給你什麼這樣反而

InputStream in = channelssh.getInputStream(); 
// channelssh.setOutputStream(baos); 

評論這條線的,看看是否確實存在這裏的東西。 另外你怎麼確定你連接? 設置命令的正確方法是這樣,所以請這樣做:

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