| 10 | import org.apache.commons.exec.PumpStreamHandler; |
| 11 | |
| 12 | public class CommandUtils { |
| 13 | private static final String DEFAULT_CHARSET = "GBK"; |
| 14 | |
| 15 | /** |
| 16 | * 执行指定命令 |
| 17 | * |
| 18 | * @param command 命令 |
| 19 | * @return 命令执行完成返回结果 |
| 20 | * @throws IOException 失败时抛出异常,由调用者捕获处理 |
| 21 | */ |
| 22 | public static String exeCommand(String command) throws IOException { |
| 23 | try ( |
| 24 | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 25 | ) { |
| 26 | int exitCode = exeCommand(command, out); |
| 27 | if (exitCode == 0) { |
| 28 | System.out.println("命令运行成功!"); |
| 29 | } else { |
| 30 | System.out.println("命令运行失败!"); |
| 31 | } |
| 32 | return out.toString(DEFAULT_CHARSET); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * 执行指定命令,输出结果到指定输出流中 |
| 38 | * |
| 39 | * @param command 命令 |
| 40 | * @param out 执行结果输出流 |
| 41 | * @return 执行结果状态码:执行成功返回0 |
| 42 | * @throws ExecuteException 失败时抛出异常,由调用者捕获处理 |
| 43 | * @throws IOException 失败时抛出异常,由调用者捕获处理 |
| 44 | */ |
| 45 | public static int exeCommand(String command, OutputStream out) throws ExecuteException, IOException { |
| 46 | CommandLine commandLine = CommandLine.parse(command); |
| 47 | PumpStreamHandler pumpStreamHandler = null; |
| 48 | if (null == out) { |
| 49 | pumpStreamHandler = new PumpStreamHandler(); |
| 50 | } else { |
| 51 | pumpStreamHandler = new PumpStreamHandler(out); |
| 52 | } |
| 53 | |
| 54 | // 设置超时时间为10秒 |
| 55 | ExecuteWatchdog watchdog = new ExecuteWatchdog(10000000); |
| 56 | |
| 57 | DefaultExecutor executor = new DefaultExecutor(); |
| 58 | executor.setStreamHandler(pumpStreamHandler); |
| 59 | executor.setWatchdog(watchdog); |
| 60 | |
| 61 | return executor.execute(commandLine); |
| 62 | } |
| 63 | |
| 64 | public static void main(String[] args) { |
| 65 | try { |
| 66 | // String result = exeCommand("E:\\tools\\nc.exe -lvvp 9000"); |
| 67 | // System.out.println(result); |
| 68 | CommandLine commandLine = CommandLine.parse("E:\\tools\\nc.exe -lvvp 9000"); |
| 69 | // CommandLine commandLine = CommandLine.parse("whoami"); |
nothing calls this directly
no outgoing calls
no test coverage detected