package com.example.demo.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import static com.sun.deploy.config.OSType.isMac;
/**
*/
@Slf4j
public class CmmondUtils {
public static Map execLinuxCMD(String cmdStr) {
try {
String[] cmd = new String[]{"/bin/sh", "-c", cmdStr};
Process ps = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
//error info
BufferedReader readError = new BufferedReader(new InputStreamReader(ps.getErrorStream()));
String lineError = null;
StringBuilder sbError = new StringBuilder();
while ((lineError = readError.readLine()) != null) {
sbError.append(lineError + "\n");
}
//log.info("linux命令执行成功。 cmd:{}, result:{} ", cmdStr, result);
Map map = new HashMap();
map.put("status", ps.waitFor());
map.put("msg", result.toString());
map.put("errorMsg", readError.toString());
return map;
} catch (Exception e) {
log.error("linux命令执行失败。cmd:{}", cmdStr, e);
}
return null;
}
public static Map execWinCMD(String cmdStr) {
BufferedReader br = null;
Process p = null;
String result = null;
try {
Runtime runtime = Runtime.getRuntime();
p = runtime.exec(cmdStr);
BufferedReader read = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = read.readLine()) != null) {
sb.append(line + "\n");
}
//error info
BufferedReader readError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String lineError = null;
StringBuilder sbError = new StringBuilder();
while ((lineError = readError.readLine()) != null) {
sbError.append(lineError + "\n");
}
Map map = new HashMap();
map.put("status", p.waitFor());
// log.info("windows命令执行成功。 cmd:{}, result:{} ",cmdStr, sb.toString());
map.put("msg", sb.toString());
map.put("errorMsg", sbError.toString());
return map;
} catch (Exception e) {
log.error("windowd命令执行失败。cmd:{}", cmdStr, e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (p != null) {
p.destroy();
}
}
return null;
}
public static Boolean isWindows() {
String os = System.getProperty("os.name");
return os.toLowerCase().startsWith("win");
}
// 根据不同平台计算md5
public static void main(String[] args) {
if (isWindows()) {
//String r = execWinCMD("md5 /data/data.txt");
Map r = execWinCMD("D:\\Program Files\\jdk1.8\\bin\\java -jar .\\ddd-service-0.0.1-SNAPSHOT.jar");
System.out.printf(r.toString());
} else if (isMac()) {
//String r = execLinuxCMD("md5 /data/data.txt");
Map r = execLinuxCMD("md5 /data/data.txt");
}
}
}