2015-05-27 64 views
0

我有方法使用j2ssh sshclient在Linux服務器上執行遠程命令。遠程命令可以從幾秒到幾分鐘之內執行。我需要Java程序等待命令完成執行後才能繼續,但事實並非如此。 Java程序運行該命令,但在遠程命令完成之前繼續運行。這裏是我的方法:j2ssh sshclient不等待遠程命令來完成

//The connect is done prior to calling the method. 

public static String executeCommand(String host, String command, String path) 
     throws Exception 
    { 
    cd(path); 
    System.out.println("-- ssh: executing command: " + command + " on " 
     + host); 

    SessionChannelClient session = ssh.openSessionChannel(); 
    session.startShell(); 

    session.getOutputStream().write("sudo -s \n".getBytes()); 
    session.getOutputStream().write(command.getBytes()); 
    session.getOutputStream().write("\n exit\n".getBytes()); 
    IOStreamConnector output = new IOStreamConnector(); 
    java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); 
    output.connect(session.getInputStream(), bos); 
    String theOutput = bos.toString(); 
    System.out.println("output..." + theOutput); 

    session.close(); 

    disconnect(); 
    return theOutput; 

    } 

回答

1

這裏的問題是,你開始外殼,輸出你的命令,然後擰斷讀操作從InputStream所以讀取另一個線程執行。您的函數的主線程立即移動到關閉會話,以便在接收到所有輸出之前您的命令將被終止。

爲了防止從會話的輸入流中直接讀取,直到它在同一線程上返回EOF,即刪除使用IOStreamConnector並手動讀入ByteArrayOutputStream。然後在流返回EOF時調用session.close(),因爲這表示從服務器接收到所有數據。

byte[] buf = new byte[1024]; 
int r; 
ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); 
while((r = session.getInputStream().read(buf)) > -1) { 
    bos.write(buf, 0, r); 
} 
0

它應該工作方式如下:

//The connect is done prior to calling the method. 

public static String executeCommand(String host, String command, String path) 
     throws Exception 
    { 
    cd(path); 
    System.out.println("-- ssh: executing command: " + command + " on " 
     + host); 

    SessionChannelClient session = ssh.openSessionChannel(); 
    if (session.executeCommand(cmd)) { 
     java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); 
    output.connect(session.getInputStream(), bos); 
    String theOutput = bos.toString(); 
    System.out.println("output..." + theOutput); 
    } 
    session.close();