2013-03-05 30 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);