0

I would like to execute

ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=dev/null -i key.txt user@host 'cd some/directory; ./check status'

on Java and read the response it gives me. Can someone please tell me how I would go about doing this?
As you see from the command, the problem is that I need to execute only one command, and I am using a private key to get into the server without using any passwords or anything of the kind. Any help will be immensely appreciated, I am bashing my head against the wall trying to solve this.

Quillion
  • 6,346
  • 11
  • 60
  • 97

3 Answers3

1

You could use Runtime and Process:

Process cmdProc = Runtime.getRuntime().exec("ssh -o ...");

Then you can process the output:

BufferedReader outReader = new BufferedReader(
                              new InputStreamReader(cmdProc.getInputStream()));
String l;
while ((l= outReader.readLine()) != null) {
   // process standard output here
}
jh314
  • 27,144
  • 16
  • 62
  • 82
1

You can use the Runtime class and split the command into pieces, stored as element of a String[] array object. Then, pass this array as an argument of the Runtime#exec(String[] args) method, which will automatically execute the specified command and arguments in a separate process.

public static void main(String[] args) throws IOException {
    Runtime rt = Runtime.getRuntime();
    String[] cmd = { "/bin/ssh", "-o", "..." };
    Process proc = rt.exec(cmd);
    BufferedReader is = 
          new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) {
        System.out.println(line);
    }
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

You can use java ProcessBuilder to execute any commands including ssh calls.

//java 7

Process p = new ProcessBuilder("ssh command here", "myArg").start();

here is more information on process builder from Oracle Java site

grepit
  • 21,260
  • 6
  • 105
  • 81