1

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 ?

3
  • I'd suggest using a native Java SSH library -- there are several -- rather than trying to go through the command-line tooling. Commented Mar 5, 2014 at 16:49
  • In particular, I've had good experiences with JSch: jcraft.com/jsch Commented Mar 5, 2014 at 16:49
  • Here you have a simple example using JSch : stackoverflow.com/a/24279641/3315914 Commented Jun 18, 2014 at 7:44

1 Answer 1

2

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"
})
Sign up to request clarification or add additional context in comments.

2 Comments

This happens to work due to the special semantics of ssh which doesn't care that Java mangles your arguments. You should never use Runtime.exec(String). Use Runtime.exec(String[]) instead.
@thatotherguy, I feel lazy now for not pointing that out. Amended appropriately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.