可以使用Java中的ProcessBuilder類來遠程執行Linux命令。下面是一個簡單的示例代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoteCommandExecutor {
public static void main(String[] args) {
String host = "your_remote_host";
String username = "your_username";
String password = "your_password";
String command = "your_command";
String sshCommand = String.format("sshpass -p %s ssh %s@%s %s", password, username, host, command);
try {
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", sshCommand);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
請注意,這個示例代碼使用了sshpass
命令來自動輸入密碼,這是因為ProcessBuilder
類無法直接在交互式登錄時輸入密碼。需要使用sshpass
或其他類似的工具來實現自動化輸入密碼。
另外,為了遠程執行命令,你需要在本地機器上安裝SSH,并確保你的Java程序有足夠的權限來連接遠程主機。