0

below is the piece of code I am running. whether I use an array pf string (cmd) or it is a single string I get an exception (see further down) while there is a passwordless login to the target Linux system.

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;  
}

The 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)

Any idea what is the cause ?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
dubi
  • 51
  • 3
  • 6

2 Answers2

5

The best way to do this in a portable manner would be to use a pure Java SSH implementation

Jsch is one of them, and a good one

It'll avoid you to cope with classpath/environnement problems while letting you send any command you want to your remote box

Grooveek
  • 10,046
  • 1
  • 27
  • 37
0

make sure you have ssh client, and it's in %PATH% (try open 'cmd' and exec ssh from there). you can also use putty or cygwin for that, or the most recommended way- use java library: SSH library for Java

Community
  • 1
  • 1
shem
  • 4,686
  • 2
  • 32
  • 43