2016-04-03 266 views
1

我想執行一個命令在一個Linux服務器上使用Android與JSch的SSH。使用「執行」通道與JSch運行命令不會返回任何輸出

據我所知我連接到服務器,但當我試圖檢索命令的結果時,我什麼都沒有。

連接到服務器:

public class SSHCommand { 

    public static String executeRemoteCommand(
      String username, 
      String password, 
      String hostname, 
      int port) throws Exception { 

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

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

     session.connect(); 

     // SSH Channel 
     ChannelExec channelssh = (ChannelExec) 
       session.openChannel("exec"); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     channelssh.setOutputStream(baos); 

     // Execute command 
     channelssh.setCommand("ls"); 
     channelssh.connect(); 
     channelssh.disconnect(); 

     return baos.toString(); 
    } 
} 

檢索數據:

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final String TAG = "TESTING"; 

     new AsyncTask<Integer, Void, Void>(){ 
      @Override 
      protected Void doInBackground(Integer... params) { 
       try { 
        Log.d(TAG, SSHCommand.executeRemoteCommand("username", "password", "192.168.0.1", 22)); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       return null; 
      } 
     }.execute(1); 
    } 
} 

缺少什麼我在這裏?

回答

2

在任何返回輸出之前,您在啓動命令後立即斷開連接。

您必須等待「exec」通道關閉(一旦命令結束,它將關閉)。

查看official JSch example for the "exec" channel

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)); 
    } 
    if(channel.isClosed()){ 
    if(in.available()>0) continue; 
    System.out.println("exit-status: "+channel.getExitStatus()); 
    break; 
    } 
    try{Thread.sleep(1000);}catch(Exception ee){} 
} 
+0

謝謝!這工作 – Will