Java Runtime.getRuntime().exec()执行linux脚本
相关文章链接:
观前提示:
本文所使用的IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Linux版本为CentOS release 6.10。
最近,在使用Java调用linux命令查询系统信息时发现,执行一些简单的脚步没有问题,但是稍微复杂的脚本变执行失败了。在百度了之后,发现加上
String[] cmd = new String[]{
"sh","-c", command};
便可成功执行。
例子如下(部分代码)
/**
* @Title getCpuInfo
* @Description 获取CPU相关信息
* @date 2020-07-29 by jjy
* @return Map<String, Object>
*/
public static Map<String, Object> getCpuInfo() {
log.info("Collect cpu info start...");
Map<String, Object> resultMap = new LinkedHashMap<>();
// 查询cpu信息
String cpuNameCommand = "cat /proc/cpuinfo | grep name | cut -f2 -d: |uniq";
// 查询cpu物理个数
String physicalCommand = "cat /proc/cpuinfo| grep \"physical id\"| sort| uniq| wc -l";
// 查看每个物理 CPU 中 core 的个数(即核数)
String coreCommand = "cat /proc/cpuinfo| grep \"cpu cores\"| uniq | cut -f2 -d:";
// 查询cpu逻辑核数
String logicCommand = "cat /proc/cpuinfo| grep \"processor\"| wc -l";
// 查询cpu空闲率
String idleCommand = "top -b -n 1 |grep Cpu | cut -d \",\" -f 4";
Process pro = null;
BufferedReader br = null;
try{
// 查询CPU信息
String[] cmd = new String[]{
"sh","-c", cpuNameCommand};
pro = Runtime.getRuntime().exec