|
@@ -0,0 +1,91 @@
|
|
|
+package com.jiayue.ipfcst.spare2.util;
|
|
|
+
|
|
|
+import cn.hutool.core.io.IoUtil;
|
|
|
+import cn.hutool.core.util.ArrayUtil;
|
|
|
+import cn.hutool.core.util.RuntimeUtil;
|
|
|
+import com.jiayue.ipfcst.common.data.entity.ProcessResult;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.apache.commons.lang3.StringUtils;
|
|
|
+
|
|
|
+import java.io.File;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.text.SimpleDateFormat;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+public class ShellUtil {
|
|
|
+
|
|
|
+ private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 执行sh命令
|
|
|
+ *
|
|
|
+ * @param cmds
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static ProcessResult runRuntime(List<String> cmds) {
|
|
|
+ log.info("开始执行");
|
|
|
+ ProcessResult processResult = new ProcessResult();
|
|
|
+ if (null == cmds || cmds.isEmpty()) {
|
|
|
+ processResult.setExitCode(1);
|
|
|
+ log.error("命令行为空!");
|
|
|
+ } else {
|
|
|
+ List<String> result = RuntimeUtil.execForLines(StandardCharsets.UTF_8, ArrayUtil.toArray(cmds, String.class));
|
|
|
+ processResult.setOutput(result);
|
|
|
+ processResult.setExitCode(0);
|
|
|
+ result.forEach(log::info);
|
|
|
+ }
|
|
|
+ log.info("执行结束");
|
|
|
+ return processResult;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 执行sh命令,可配置环境变量及工作路径
|
|
|
+ *
|
|
|
+ * @param cmds
|
|
|
+ * @param envs
|
|
|
+ * @param workspace
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public static ProcessResult runProcess(List<String> cmds, Map<String, String> envs, File workspace) {
|
|
|
+ log.info("开始执行");
|
|
|
+ Process process = null;
|
|
|
+ ProcessResult result = new ProcessResult();
|
|
|
+ List<String> message;
|
|
|
+ try {
|
|
|
+ ProcessBuilder processBuilder = new ProcessBuilder();
|
|
|
+ processBuilder.command(cmds);
|
|
|
+ //命令工作空间
|
|
|
+ if (null != workspace && workspace.exists() && workspace.isDirectory()) {
|
|
|
+ processBuilder.directory(workspace);
|
|
|
+ }
|
|
|
+ //环境变量
|
|
|
+ if (null != envs) {
|
|
|
+ Map<String, String> enviroment = processBuilder.environment();
|
|
|
+ for (String key : envs.keySet()) {
|
|
|
+ if (enviroment.containsKey(key)) {
|
|
|
+ if (!StringUtils.equals(enviroment.get(key), envs.get(key))) {
|
|
|
+ enviroment.put(key, envs.get(key));
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ enviroment.put(key, envs.get(key));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ log.info(String.join(" ", processBuilder.command()));
|
|
|
+ //执行命令
|
|
|
+ process = processBuilder.start();
|
|
|
+ message = IoUtil.readUtf8Lines(process.getInputStream(), new ArrayList<>());
|
|
|
+ result.setOutput(message);
|
|
|
+ result.setExitCode(0);
|
|
|
+ } catch (Exception ex) {
|
|
|
+ result.setExitCode(1);
|
|
|
+ } finally {
|
|
|
+ RuntimeUtil.destroy(process);
|
|
|
+ log.info("执行结束");
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+}
|