共計 994 個字符,預計需要花費 3 分鐘才能閱讀完成。
可以使用 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 程序有足夠的權限來連接遠程主機。
丸趣 TV 網 – 提供最優質的資源集合!
正文完