我需要将文本参数通过管道传递给使用 Apache Commons Exec 启动的命令的标准输入(出于好奇,命令是 gpg,参数是 keystore 的密码;gpg 没有提供密码的参数明确地,只从标准输入接受它)。
此外,我需要它同时支持 Linux 和 Windows。
在 shell 脚本中我会这样做
cat mypassphrase|gpg --passphrase-fd
或
type mypassphrase|gpg --passphrase-fd
但 type 在 Windows 上不起作用,因为它不是可执行文件,而是解释命令 (cmd.exe) 中内置的命令。
代码 不起作用(由于上述原因)如下。为此生成整个 shell 太丑陋了,我一直在寻找更优雅的解决方案。不幸的是,BouncyCaSTLe 库和 PGP 之间存在一些不兼容问题,因此我无法在(非常短的)时间内使用完全编程的解决方案。
提前致谢。
CommandLine cmdLine = new CommandLine("type");
cmdLine.addArgument(passphrase);
cmdLine.addArgument("|");
cmdLine.addArgument("gpg");
cmdLine.addArgument("--passphrase-fd");
cmdLine.addArgument("0");
cmdLine.addArgument("--no-default-keyring");
cmdLine.addArgument("--keyring");
cmdLine.addArgument("${publicRingPath}");
cmdLine.addArgument("--secret-keyring");
cmdLine.addArgument("${secretRingPath}");
cmdLine.addArgument("--sign");
cmdLine.addArgument("--encrypt");
cmdLine.addArgument("-r");
cmdLine.addArgument("recipientName");
cmdLine.setSubstitutionMap(map);
DefaultExecutor executor = new DefaultExecutor();
int exitValue = executor.execute(cmdLine);
最佳答案
您不能添加管道参数 (|
),因为 gpg
命令不会接受它。当您将命令行键入 shell 时,解释管道并执行特殊处理的是 shell(例如 bash
)。
您可以使用 ByteArrayInputStream
手动将数据发送到命令的标准输入(很像 bash
在看到 |
时所做的) .
Executor exec = new DefaultExecutor();
CommandLine cl = new CommandLine("sed");
cl.addArgument("s/hello/goodbye/");
String text = "hello";
ByteArrayInputStream input =
new ByteArrayInputStream(text.getBytes("ISO-8859-1"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
exec.setStreamHandler(new PumpStreamHandler(output, null, input));
exec.execute(cl);
System.out.println("result: " + output.toString("ISO-8859-1"));
这应该等同于键入 echo "hello"| sed s/hello/goodbye/
到 (bash
) shell(尽管 UTF-8 可能是更合适的编码)。
关于java - 如何将字符串参数传递给使用 Apache Commons Exec 启动的可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695664/