Search code examples
javasshprocessbuilder

ProcessBuilder and ssh to invoke remote command


from one Linux machine, I want to run a command on a remote Linux machine as follows:

ssh remote_user@remote_server remote_command < local_script

Here remote_command is a command to run on the remote machine and local_script is a file on the local machine that contains a string to pass to the remote_command. If I run this at the command line on my local machine, then I can verify that the command has the right effect on the remote machine. However, I need to run this within a Java application using ProcessBuilder as follows:

processBuilder = new ProcessBuilder("ssh remote_user@remote_server remote_command < local_script");
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
process = processBuilder.start();

When I do this, I always get the error:

zsh:1: no such file or directory: local_script

I have tried variations such as:

processBuilder = new ProcessBuilder("ssh", "remote_user@remote_server remote_command < local_script");
processBuilder = new ProcessBuilder("ssh", "remote_user@remote_server", "remote_command < local_script");
processBuilder = new ProcessBuilder("ssh", "remote_user@remote_server", "remote_command", "<", " local_script");

but nothing seems to work. I have verifed that running pwd gives the expected directory and that the local_script can be read (using cat) when run using ProcessBuilder, so I have to assume it's something to do with the way that the ssh command is being handled. Any ideas?


Solution

  • You have 3 choices:

    • wrap your query in a "sh" call so that the "<" is processed by bash not by java ( ProcessBuilder("sh","-c","ssh xxxxx yyyy < zzz"); (and be ware of file location!)
    • remove the "< local_script" and use the processBuider.redirectInput().from(new File(local_script)); to inject the data in input stream
    • use a thrid party library to manage ssh from java (like JSch)