使用java Runtime(在windows机器上)将linux命令发送到linux服务器

dub*_*ubi 0 java runtime runtime.exec

下面是我正在运行的代码片段.我是否使用数组pf字符串(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;  
}
Run Code Online (Sandbox Code Playgroud)

例外:

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)
Run Code Online (Sandbox Code Playgroud)

不知道是什么原因?

Gro*_*eek 5

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

Jsch是其中之一,也是一个很好的

它可以避免你应对类路径/环境问题,同时让你发送任何你想要的命令到你的远程盒子