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

时间:2012-03-30 13:25:55

标签: 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;  
}

例外:

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)

任何想法是什么原因?

2 个答案:

答案 0 :(得分:5)

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

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

在让您将任何命令发送到远程信箱时,它可以避免您应对类路径/环境问题

答案 1 :(得分:0)

确保你有ssh客户端,并且它在%PATH%中(尝试从那里打开'cmd'和exec ssh)。 你也可以使用putty或cygwin,或者最推荐的方式 - 使用java库:SSH library for Java