简体   繁体   中英

Copy using Apache Commons Exec

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);
commandLine.addArgument(target + destination,false);

public CommandLine addArguments(String addArguments, boolean handleQuoting)

this worked !!

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