我正在使用 apache commons exec 运行命令:arp | wc -l
下面是我的代码:
private String runCommand(String cmd, String params) {
CommandLine commandLine = new CommandLine(cmd);
commandLine.addArguments(params);
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdout, stderr);
ExecuteWatchdog watchdog = new ExecuteWatchdog(30000); // 30s timeout
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(pumpStreamHandler);
executor.setWatchdog(watchdog);
try {
int retCode = executor.execute(commandLine);
System.out.println("Executed '" + cmd + "'\n"
+ "returnCode: " + retCode + "\n"
+ "stdout:\n" + stdout.toString() + "\n"
+ "stderr:\n" + stderr.toString());
if (retCode == 0) {
return stdout.toString();
} else {
throw new NonZeroExitStatusReturnedException(commandLine.toString(), retCode);
}
} catch (IOException e) {
throw new RuntimeException("Could not run command "+ commandLine.toString(), e);
}
}
这里是 cmd/bin/sh
和 params-c arp|wc-l
代码给出以下输出:
Executed '/bin/sh'
returnCode: 0
stdout:
54 71 4321
stderr:
usage: arp [-n] [-i interface] hostname
arp [-n] [-i interface] [-l] -a
arp -d hostname [pub] [ifscope interface]
arp -d [-i interface] -a
arp -s hostname ether_addr [temp] [reject] [blackhole] [pub [only]] [ifscope interface]
arp -S hostname ether_addr [temp] [reject] [blackhole] [pub [only]] [ifscope interface]
arp -f filename
我在这里有两个问题:
问题 1。我不明白为什么我的输出中有三个数字(54 71 4321)。不应该只有一个数字吗?
问题2。有没有更好的方法来使用 apache commons exec 运行相同的命令?