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

Class ToolShell

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

shell相关工具 @author SeanDragon

Source from the content-addressed store, hash-verified

15 * @author SeanDragon
16 */
17public final class ToolShell {
18
19 private ToolShell() {
20 throw new UnsupportedOperationException("我是工具类,别初始化我。。。");
21 }
22
23 /**
24 * 是否是在root下执行命令
25 *
26 * @param toolCommandExec
27 * 包含下面四个属性 commands 命令数组 isRoot 是否需要root权限执行 isNeedResultMsg 是否需要结果消息 isNeedEnter
28 * 是否需要回车
29 *
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);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected