利用 Runtime.exec 方法,我們可以在 Java 程序中運行 Linux 的 Shell 腳本,或者執行其他外部程序。本文封裝了一個帶超時控制的 CommandHelper 工具類。
package javaapplication3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CommandHelper {
// 默認超時時間,單位毫秒
public static int DEFAULT_TIMEOUT;
public static final int DEFAULT_INTERVAL = 1000;
public static long START;
public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
CommandResult commandResult = wait(process);
if (process != null) {
process.destroy();
}
return commandResult;
}
private static boolean isOverTime() {
return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
}
private static CommandResult wait(Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 超時控制
START = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}
try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// 進程尚未結束
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}
} finally {
if (errorStreamReader != null) {
try { errorStreamReader.close(); } catch (IOException e) {}
}
if (inputStreamReader != null) {
try { inputStreamReader.close(); } catch (IOException e) {}
}
}
}
}
CommandHelper 使用 CommandResult 對象封裝輸出與錯誤信息,該類實現如下:
package javaapplication3;
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT = -1;
private String output;
void setOutput(String error) { output = error; }
String getOutput() { return output; }
int exitValue;
void setExitValue(int value) { exitValue = value; }
int getExitValue() { return exitValue; }
private String error;
public String getError() { return error; }
public void setError(String error) { this.error = error; }
}
調用演示(main 函數接收一個超時參數):
public static void main(String[] args) {
try {
int timeout = Integer.parseInt(args[0]);
CommandHelper.DEFAULT_TIMEOUT = timeout;
CommandResult result = CommandHelper.exec("mkdir testdir");
if (result != null) {
System.out.println("Output:" + result.getOutput());
System.out.println("Error:" + result.getError());
}
} catch (IOException ex) {
System.out.println("IOException:" + ex.getLocalizedMessage());
} catch (InterruptedException ex) {
System.out.println("InterruptedException:" + ex.getLocalizedMessage());
}
}
執行後會創建一個 testdir 目錄。在實踐中我嘗試用這種方法通過 SSH 登錄遠程機器,遇到幾個問題:其一,若希望無人機對話,需要使用 sshpass -p password ssh user@targetIP 'command';其二,直接在 IDE 中運行可能因權限不足而失敗,需要在終端中執行;其三,很多命令無法運行,僅 pwd 等少數命令可用,原因尚不明確。遇到復雜場景時,建議改用 Ganymed SSH-2 庫或其他類似的 Java 庫。