2016-06-29 166 views
1
String ipAddress = address.getHostAddress(); 
responseObject.put("ipAddress", ipAddress); 
String loginCommand = COMMAND_SSH + userName + "@" + ipAddress; 
Process remoteProcess = Runtime.getRuntime().exec(loginCommand); 
PrintStream out = new PrintStream(remoteProcess.getOutputStream()); 
BufferedReader in = new BufferedReader(new InputStreamReader(remoteProcess.getInputStream())); 
//out.println(password); 
while (in.ready()) { 
    String s = in.readLine(); 
    LOGGER.info(s); 
} 
out.println(COMMAND_EXIT); 

上面的代碼調試退出時總是顯示remoteProcess已退出與代碼255,我想不通爲什麼?我試圖用ls替換loginCommand,它工作正常嗎?我可以知道我出錯的地方嗎?SSH遠程命令碼255

P.S:我不允許使用外部庫(包括OS)。

+0

考慮將錯誤輸出重定向到標準輸出或讀取錯誤輸出。 – user254948

回答

0

你的代碼有幾個問題,但沒有一個必須是你的問題的確切原因,因爲沒有足夠的代碼給出。

while (in.ready()) { 
    String s = in.readLine(); 
    LOGGER.info(s); 
} 

in.ready()在流準備就緒時返回true。你在這裏引入競爭條件。如果在插入準備就緒之前達到了while(),則會跳過整個語句。 而是使用:

String s; 
while ((s = in.readLine()) != null){ 
    LOGGER.info(s); 
} 

此外,您可能希望確保您也可以參考標準錯誤輸出。

+0

謝謝:)我一定會嘗試一下,告訴你它是如何發生的。這也是代碼的主要部分,其餘部分只是接收參數 –

+0

@MageshKumaar你的代碼不顯示你如何獲得COMMAND_EXIT,COMMAND_SSH也沒有顯示;) – user254948

+0

那些是最終的字符串,它們的值是'ssh'和'出口' –