使用 Apache Commons Exec 复制

Copy using Apache Commons Exec

我正在尝试使用 Apache Commons API 执行复制命令。以下是我的努力:

   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);

输出:

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)

相同的程序在没有 space 的目标文件夹中工作正常:

字符串目的地="/Leo/Ta/SanJose";

scp -i /Users/TD/.ssh/id_rsa /Users/TD/One.txt root@my.server.com:/Leo/Ta/SanJose

不构造命令字符串,而是使用 CommandLine 的 addArgument 方法。这将确保您的命令在语法上是正确的。

下面的代码演示了它:

    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)

这有效!!