简体   繁体   中英

Run command remotely using Java

I need to run a command remotely using java. The command works if I run it in the command line, but not inside java.

Command

ssh slave1 -t 'pkill script.sh'

Java code

import java.io.*;

public class JavaKillScriptCommand {
   public static void main(String args[]) {

   String node = "1.2.3.4";
   try{
     Process p = Runtime.getRuntime().exec("ssh " + node + " -t 'pkill script.sh'");
   } catch (IOException e){
     System.out.print("'pkill script.sh' command through an exception");
     }
  }
}

Any help?

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM