【问题标题】:Copy using Apache Commons Exec使用 Apache Commons Exec 复制
【发布时间】:2015-08-26 03:40:16
【问题描述】:

我正在尝试使用 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:进程退出并出现错误:1(退出值:1)

相同的程序可以在没有空间的目标文件夹中正常工作:

String destination="/Leo/Ta/SanJose";

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

【问题讨论】:

    标签: java apache-commons-exec


    【解决方案1】:

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

    下面的代码演示了它:

        CommandLine commandLine = new CommandLine("scp");
        commandLine.addArgument("-i", false);
        commandLine.addArgument(privateKey, false);
        commandLine.addArgument(currentFile, false);
        commandLine.addArgument(target + destination, false);
    

    【讨论】:

    • 感谢您的回复!我添加了提到的参数,但仍然得到“org.apache.commons.exec.ExecuteException:进程退出并出现错误:1(退出值:1)现在的输出是:scp -i /Users/TD/.ssh/id_rsa /用户/TD/One.txt "root@my.server.com:/Leo/Ta/San\ Diego"
    • 打印出命令并从 shell 执行,看看你得到什么消息。
    • 打印命令:scp -i /Users/TD/.ssh/id_rsa /Users/TD/One.txt "root@my.server.com:/Leo/Ta/San\ Diego"
    • “目标 + 目的地”的连接出现了带引号的情况,这会产生问题
    • 您是否删除了此声明:destination=destination.replaceAll(" ", "\\\\ ");
    【解决方案2】:
    commandLine.addArgument(target + destination,false);
    

    公共命令行 addArguments(String addArguments, boolean 处理报价)

    成功了!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 2019-04-30
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多