2012-03-30 14 views
0

下面是我正在运行的代码片段。无论我使用数组pf字符串(cmd)还是它是 单个字符串,我都会在进行无密码登录到目标Linux系统时出现异常(请参阅下面的内容)。使用java运行系统(在Windows机器上)发送linux命令到linux服务器

private static int bringHostFile() { 
    try {    
     String[] cmd ={"ssh" , "[email protected]" , "/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) 

任何想法的原因是什么?

+3

“系统找不到指定的文件”:在程序的%PATH%中是'ssh'? – Mat 2012-03-30 13:28:07

+0

或者,您的Windows计算机上没有安装'ssh'客户端。 – nobeh 2012-03-30 13:29:04

+0

如果'ssh'不在你的路径中,你可以指定'ssh'的完整路径。 – 2012-03-30 16:26:08

回答

5

做到这一点在便携方式是使用纯Java SSH实现的最佳途径

Jsch就是其中之一,而一个好的

它会避免你应付的classpath/environnement问题,同时让你发送你想要的任何命令到你的远程盒子

0

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

相关问题