如何使用commons-exec执行/ bin/sh?

yeg*_*256 2 java apache-commons-exec

这就是我正在做的事情:

import org.apache.commons.exec.*;
String cmd = "/bin/sh -c \"echo test\"";
new DefaultExecutor().execute(CommandLine.parse(cmd));
Run Code Online (Sandbox Code Playgroud)

这是输出:

/bin/sh: echo test: command not found
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Chr*_*röm 8

根据FAQ "建议使用CommandLine.addArgument()而不是CommandLine.parse()".

所以试试吧

CommandLine commandLine = new CommandLine("/bin/sh");
commandLine.addArgument("-c");
commandLine.addArgument("echo test", false); // false is important to prevent commons-exec from acting stupid
executor.execute(commandLine);
Run Code Online (Sandbox Code Playgroud)