java - 使用java运行时(在Windows机器上)将Linux命令发送到Linux服务器

标签 java runtime runtime.exec

下面是我正在运行的代码片段。我是否使用数组 pf string (cmd) 或者它是 当对目标 Linux 系统进行无密码登录时,我会得到一个字符串异常(请参阅下文)。

private static int bringHostFile() {
    try {            
        String[] cmd ={"ssh" , "root@im6-64s" , "/root/bring_hosts"};
   Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

        String s = null;
        // read the output from the command
        if ((s = stdInput.readLine()) != null) {
            System.out.println(s);     
         }

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
               System.out.println(s);
        }            

    }
    catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }   

    return 0;  
}

异常(exception):

java.io.IOException: Cannot run program "ssh": CreateProcess error=2, The system cannot find the file specified.
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:471)
    at java.lang.Runtime.exec(Runtime.java:604)
    at java.lang.Runtime.exec(Runtime.java:442)
    at java.lang.Runtime.exec(Runtime.java:339)
    at JavaRunCommand.CommandGetCurrentCPUSize(JavaRunCommand.java:140)
    at EC.<init>(EC.java:29)

知道原因是什么吗?

最佳答案

以可移植方式执行此操作的最佳方法是使用纯 Java SSH 实现

Jsch是其中之一,而且是一个很好的

它将避免您处理类路径/环境问题,同时让您可以向远程设备发送任何您想要的命令

关于java - 使用java运行时(在Windows机器上)将Linux命令发送到Linux服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9943899/

相关文章:

java - 在java中运行程序读取它在做什么

java - 无法解析导入 - Visual Studio Code for Java

java - 当我们使用 throws 时,谁以及如何处理异常?

java - Arquillian/收缩包装 : How to replace jar or class folder from a WAR?

C# Winform 运行时加载 Windows 窗体 Controller 库

python - 按索引删除列表元素是否比按值删除更有效?

java - 如何在Java中存储执行.exe文件时生成的文件?

java - 错误类消息创建方式

colors - 在运行时更改文本颜色(Unity)?

java - 在 Eclipse 中运行外部程序