How to Execute Linux Commands on a Remote MAChine Using Java

Run linux command in remote machine from java

Luis: as Eric suggested one possible solution is to run a local script that performs an SSH itself on the remote server.

For instance if you have a Linux->Linux environment, your script you could have something like:

ssh remoteuser@remotehost 'bash -s' < localscripttoexecuteremotely.sh

In a Windows->Linux scenario you could do:

plink remoteuser@remotehost -m localscripttoexecuteremotely.sh

Take a look at this thread for additional information.

run process (command) on a remote linux machine from java

Yes you can, one of the way:

  • On your target server(yyy.yyy.yyy.yyy), run a process that listens for commands from your client machine(xxx.xxx.xxx.xxx) . There are different ways to communicate between two remote jvms, you may chose any of them for example socket communication.

  • On target machine JVM, you can use ProcessBuilder to run the command received from client machine.

Or just some search for frameworks already available to such a task.

Run command remotely using Java

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.

Execute a local script on a remote machine through Java JSch library

You cannot execute a local script on a server.

You have two options (that you are obviously aware of):

  • Upload the script and execute it (and delete afterwards, if needed).
  • Execute the contents of the script. As you already know, just concatenate all lines with ;.

    Though be careful about the for and if. There should be no ; after the do and then.

    cd /log ; searchString='<Error ErrorCode="java.sql.SQLException"' ; files=`find . -mmin -60 -type f -exec ls {} +` ; echo `pwd` ; echo `hostname` ; echo ${files} ; for file in ${files[@]} ; do if grep -Fq "$searchString" $file ; then echo "String found in $file" ; fi ; done
  • Similarly to the previous approach, you can execute the bash -s and write the contents of the script (the commands) to its input.

    ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
    channelExec.setCommand("bash -s");
    channelExec.connect();
    OutputStream out = channel.getOutputStream();
    FileInputStream fis = new FileInputStream("testScript.sh");
    byte[] buf = new byte[1024];
    while (true)
    {
    int len = fis.read(buf, 0, buf.length);
    if (len <= 0) break;
    out.write(buf, 0, len);
    }

    The above is basically copied from seemingly unrelated SCP upload example - That example actually feeds a local file to remote scp process - So it's actually pretty related.


Ntb, "echo `pwd`" and "echo `hostname`" do not make sense. Use "pwd" and "hostname" directly.



Related Topics



Leave a reply



Submit