阅读量:0
可以使用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程序有足够的权限来连接远程主机。