Mehdi
Mehdi

Reputation: 2228

run bash commande by ssh using Java

I want to run a script with ssh from java. The script takes a number as parameter. I launch this code :

String myKey="/home/my_key.pem";
Runtime runtime = Runtime.getRuntime();

String commande = "ssh -i "
+myKey+" [email protected] './runScript.bash 8000'";
Process p = runtime.exec(commande);      

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = reader.readLine();
while (line != null) {

System.out.println(line);
line = reader.readLine();
}

p.waitFor();

I obtain this error :

bash: ./runScript.bash 8000: No such file or directory

The name of file is correct. chmod given to runScript.bash is 777.

When i run the command line directly from bash it works. But from IDE, it does not.

How can i do to run this commande line correctly please ?

Upvotes: 1

Views: 761

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295272

The error makes it clear:

bash: ./runScript.bash 8000: No such file or directory

This indicates that the shell is trying to invoke a script called ./runScript.bash 8000 -- with the space and the 8000 in the filename of the script.

It's rare for me to be telling anyone to use fewer quotes, but, well, this is actually a case where that would fix things.

Better would be to avoid double evaluation altogether:

Runtime.exec(new String[] {
   "ssh",
   "-i", myKey,
   "[email protected]",
   "./runScript 8000"
})

Upvotes: 2

Related Questions