MCPcopy Create free account
hub / github.com/SeanDragon/protools / execCmd

Method execCmd

common/src/main/java/pro/tools/system/ToolShell.java:32–88  ·  view source on GitHub ↗

是否是在root下执行命令 @param toolCommandExec 包含下面四个属性 commands 命令数组 isRoot 是否需要root权限执行 isNeedResultMsg 是否需要结果消息 isNeedEnter 是否需要回车 @return ToolCommandResult

(ToolCommandExec toolCommandExec)

Source from the content-addressed store, hash-verified

30 * @return ToolCommandResult
31 */
32 public static ToolCommandResult execCmd(ToolCommandExec toolCommandExec) throws IOException {
33 int result = -1;
34 if (toolCommandExec.getCommands() == null || toolCommandExec.getCommands().length == 0) {
35 return new ToolCommandResult(result, null, null);
36 }
37
38 String[] commands = toolCommandExec.getCommands();
39 boolean isNeedResultMsg = toolCommandExec.isNeedResultMsg();
40 boolean isNeedEnter = toolCommandExec.isNeedEnter();
41
42 Process process = null;
43 StringBuilder successMsg = null;
44 StringBuilder errorMsg = null;
45
46 try {
47 process = Runtime.getRuntime().exec(ToolSystem.isWindows() ? "cmd" : "sh");
48 try (DataOutputStream os = new DataOutputStream(process.getOutputStream())) {
49 for (String command : commands) {
50 if (command == null) {
51 continue;
52 }
53 os.write(command.getBytes());
54 os.writeBytes("\n");
55 os.flush();
56 }
57 os.writeBytes("exit\n");
58 os.flush();
59 result = process.waitFor();
60 } catch (InterruptedException | IOException e) {
61 e.printStackTrace();
62 }
63 if (isNeedResultMsg) {
64 try (BufferedReader successResult = new BufferedReader(new InputStreamReader(process.getInputStream(), StrConst.DEFAULT_CHARSET_NAME));
65 BufferedReader errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream(), StrConst.DEFAULT_CHARSET_NAME))) {
66 successMsg = new StringBuilder();
67 errorMsg = new StringBuilder();
68 String s;
69 char entry = isNeedEnter ? '\n' : ' ';
70 while ((s = successResult.readLine()) != null) {
71 successMsg.append(s).append(entry);
72 }
73 while ((s = errorResult.readLine()) != null) {
74 errorMsg.append(s).append(entry);
75 }
76 }
77 }
78 } finally {
79 if (process != null) {
80 process.destroy();
81 }
82 }
83 return new ToolCommandResult(
84 result,
85 successMsg == null ? null : successMsg.toString(),
86 errorMsg == null ? null : errorMsg.toString()
87 );
88 }
89

Callers 2

installMethod · 0.95
jarMethod · 0.95

Calls 7

isWindowsMethod · 0.95
getCommandsMethod · 0.80
isNeedResultMsgMethod · 0.80
isNeedEnterMethod · 0.80
writeMethod · 0.80
writeBytesMethod · 0.80
toStringMethod · 0.45

Tested by

no test coverage detected