Add: neardupe Why does Runtime.exec(String) work for some but not all commands?
and Java Runtime.getRuntime().exec(cmd) command contain single quote
Runtime.exec(String)
is not the same as typing a command to a shell. It does not interpret quotes the way a shell does but instead tokenizes at all whitespace, 'quoted' or not. (It also doesn't handle redirection, pipes, multiple commands of all types, parameters (aka variables), process substitution, builtins, functions, and aliases.) In general to get specific tokenization you should use one of the overloads taking String[]
or (usually even better) ProcessBuilder
.
But in this case ssh
doesn't require the remote command be a single argument; it accepts multiple arguments, so
Runtime.exec ("ssh " + node + " -t pkill script.sh");
will work, as long as the name script.sh
does not contain any character(s) special to the shell. (Obviously assuming you are able to automatically e.g. publickey authenticate to the target under your default=same or ssh-configured id, and that id has authority to kill any relevant script.sh process.)
Only failing to start the specified program (here ssh) throws a Java exception; any errors that occur during execution of the program -- such as an error ssh encounters in connecting to the target or running the command -- are reported either on stderr or stdout (.getErrorStream()
and .getInputStream()
) and/or in the process' exit status (.waitFor()
), and you ignored all of those. Also, the past tense of throw is threw not through.