joule_wonder
joule_wonder

Reputation: 11

Java program to run shell commands from a windows machine

I am trying to run a Java program to shell out commands on a remote (Linux) machine. I can get the putty.exe to run and then connect to the machine using SSH keys. But am not able to run the actual commands such as "bash" "ps-ef" or "ls -la". Currently using the Java runtime.exec, not sure if using the java.lang.ProcessBuilder would help? What am I doing wrong ? Any help/guidance would be greatly appreciated.. Thanks in advance

package hello;

import java.io.*;
public class RuntimeExample {




     public static void main(String args[]) throws IOException {



    try{     


    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(new String[]{"C:\\Users\\yky90455\\Desktop\\putty.exe","[email protected]","bash", "ps -ef"});


    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;

    System.out.printf("Output of running the command is:");

    while ((line = br.readLine()) != null) {
        System.out.println(line);

      }                                                             

    } catch (Exception e) {
        e.printStackTrace();
    }
}   

}

Upvotes: 0

Views: 2246

Answers (4)

SATHIYA B
SATHIYA B

Reputation: 1

public class triggerPutty {
    public static void main(String[] a) {
        try {
            String command = "putty.exe [email protected] -pw password -m C:\\containing_comman.txt";
            Runtime r = Runtime.getRuntime();
            Process p = null;
            p = r.exec(command);
            p.waitFor();
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }
}

-m helps to run your command from that file.
You can keep N number of commands in that file.. ## Heading ##

Upvotes: -1

joule_wonder
joule_wonder

Reputation: 11

Thanks for all your answers. I tried Ganymed SSH-2 library. It works well for the basic commands on the remote machine. I will have to explore other APIs in case I run into any limitation with SSH-2.

Upvotes: 0

Rai
Rai

Reputation: 394

Also consider ExpectJ which is a wrapper around TCL Expect. The project does not appear to have any active development since mid 2010, but I have used it for SSH in the past.

http://expectj.sourceforge.net/apidocs/expectj/SshSpawn.html

Upvotes: 0

Shashank Vivek
Shashank Vivek

Reputation: 17504

try Jsch From here to get the shell scrips executed from Java to some remote Linux machine. I have worked on this and it was really fun.although you may find little shortage of docs for understanding this but you can overcome that easily.

Upvotes: 2

Related Questions