0

I am trying to copy a file via ssh from remote server to client. When executing my command on cli, the file is being copied to the correct location. But if I am executing the exactly same command via Java, the file is being copied to the remote machines directory instead of the clients one.

This is the command I am using (I am using a key s.t. no password has to be entered):

ssh -i /home/user/.ssh/id_rsa -C -p 2201 test@localhost 'cat /opt/test/file.txt' > /home/user/file.txt

And this is the code, quite simple:

Process p;
p = Runtime.getRuntime().exec("ssh -i /home/user/.ssh/id_rsa -C -p 2201 test@localhost 'cat /opt/test/file.txt' > /home/user/file.txt");

Any idea why the file is being copied to the wrong machines directory and how to get it copied to the clients directory instead, when executing the command using java?

stl
  • 63
  • 1
  • 11
  • Can you try to put the full path of the destination? – Pitto Aug 07 '19 at 09:02
  • I tried, but the effect is the same. If the path exists on remote machine, the file will be copied to this directory (but I want it on client). If it doesn't exist, the file won't be copied at all. – stl Aug 07 '19 at 09:06
  • When using `Runtime` stdin and stdout is handled differently. See this [question](https://stackoverflow.com/q/882772/1616627) on suggestions on how to do it. Your `>` in the command is passed to the server. – Roger Gustavsson Aug 07 '19 at 09:25

1 Answers1

0

Don't use > in the command. Read the data via an InputStream retrieved from the resulting Process object. As with ~ mentioned in an earlier version of the question, > is a shell specific feature, and a shell isn't involved in exec().

Process p = Runtime.getRuntime().exec("your command");
p.waitFor();
InputStream commandOutput = p.getInputStream();

Read from this stream and write it to a file.

Alternative:

Try

p = Runtime.getRuntime().exec("sh -c ssh -i /home/user/.ssh/id_rsa -C -p 2201 test@localhost 'cat /opt/test/file.txt' > /home/user/file.txt");
Community
  • 1
  • 1
Roger Gustavsson
  • 1,689
  • 10
  • 20