【问题标题】:Quotes in Command Line命令行中的引号
【发布时间】:2013-01-09 16:19:03
【问题描述】:

我正在尝试为 LFTP 制作一个 maven 插件,这涉及从我的 java 应用程序调用 LFTP 命令行程序。

但是我无法让它使用单引号、双引号、转义单/双引号处理我传入的命令。

到目前为止,我所拥有的代码是:

final String command = "lftp -e 'set ftp:ssl-protect-data true; put -O /data/upload/ src/test/resources/test-file.txt; bye' -u username,password -p 21 192.168.1.100"
final CommandLine cmdLine = CommandLine.parse(command.toString());
final DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(new File(baseDir));
final int result = executor.execute(cmdLine);

以及寻找关于下一步尝试的建议。

编辑 #1: 我尝试使用 org.apache.commons.exec.CommandLine 并作为预先完成的字符串,但会导致以下错误:

Unknown command `set ftp:ssl-protect-data true; put -O /data/upload/ src/test/resources/test-file.txt; bye'.
Exception in thread "main" org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
    at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:377)
    at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:160)
    at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:147)
    at org.welsh.build.automation.lftp.plugin.TestClass.main(TestClass.java:30)

但是当我打印出生成的命令并手动运行它时,它工作正常。

编辑#2:增加了一些清晰度。

【问题讨论】:

  • 难道没有某种执行器将字符串数组作为参数而不是单个字符串?
  • @baba 我不认为这是相关的,因为这里是执行外部命令的问题
  • @fge 是否外部,不推荐使用 sun API。这就是为什么像 Commons Cli 这样更好的库与尝试使用已弃用的 API 手动解析引号和单引号相比可以创造奇迹的原因。
  • @baba 我认为他正试图从他的程序中执行一个外部命令,而不是编写一个接受命令行选项的程序。

标签: java command-line lftp


【解决方案1】:

Commons-exec 强调通过增量构建更容易处理 CommandLine 实例:

final CommandLine cmdLine = new CommandLine("lftp");
cmdLine.addArgument("-e");
cmdLine.addArgument("set ftp:ssl-protect-data true; put -O /data/upload/ src/test/resources/test-file.txt; bye");
...
executor.execute(cmdLine);

我没有看过他们的命令行解析器,但如果他们不完全信任它,我也不会。

【讨论】:

  • 我试图利用它,但它在我的编辑中产生了错误。在发送中,应该用引号括起来的内容被视为第二个命令,而不是 LFTP 命令的一部分。
【解决方案2】:

这里有一些例子:

Apache Commons Exec

请注意,它们不使用单引号 (') 字符,而是通过在双引号字符前加上反斜杠来构建带有双引号的 java 字符串。

这是一个例子:

String line = "AcroRd32.exe /p /h \"" + file.getAbsolutePath() + "\"";

这是另一种构建命令行的方法:

CommandLine cmdLine = new CommandLine("lftp");
cmdLine.addArgument("-e");
cmdLine.addArgument("set ftp:ssl-protect-data true; put -O /data/upload/ src/test/resources/test-file.txt; bye");
cmdLine.addArgument("-u");
cmdLine.addArgument("username,password");
cmdLine.addArgument("-p");
cmdLine.addArgument("21");
cmdLine.addArgument("192.168.1.100");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多