I am trying to execute a copy command using Apache Commons API. Below is my effort :
String privateKey = "/Users/TD/.ssh/id_rsa";
String currentFile = "/Users/TD/One.txt";
String target = "root@my.server.com:";
// Space is present in destination
String destination="/Leo/Ta/San Diego";
CommandLine commandLine = new CommandLine("scp");
commandLine.addArgument("-i");
commandLine.addArgument(privateKey);
commandLine.addArgument(currentFile);
commandLine.addArgument(target + destination);
System.out.println(commandLine.toString());
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(0);
executor.execute(commandLine);
Output :
scp -i /Users/TD/.ssh/id_rsa /Users/TD/One.txt "root@my.server.com:/Leo/Ta/San Diego"
org.apache.commons.exec.ExecuteException: Process exited with an error: 1(Exit value: 1)
Same program works fine with destination folder with no space in it:
String destination="/Leo/Ta/SanJose";
scp -i /Users/TD/.ssh/id_rsa /Users/TD/One.txt root@my.server.com:/Leo/Ta/SanJose
Instead of constructing the command string, use CommandLine's addArgument
method. That will ensure that your command is syntactically correct.
The following code demonstrates it:
CommandLine commandLine = new CommandLine("scp");
commandLine.addArgument("-i", false);
commandLine.addArgument(privateKey, false);
commandLine.addArgument(currentFile, false);
commandLine.addArgument(target + destination, false);