//单条命令执行,iostat -x|awk -F ' ' '{print $2}' 这条语句,下面方法不会执行awk命令,报错了
//该方法是hutool提供的
String str = RuntimeUtil.execForStr("ipconfig");
//这样处理可以支持管道命令不生效的问题
String[] command ={"/bin/sh", "-c", "iostat -x | awk -F ' ' '$14>0' | awk '{print $14}'"};
String res = RuntimeUtil.execForStr(command);
//如果不成功,肯能是服务器不支持命令
//hutool依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.12</version>
</dependency>
/**
* 执行系统命令
*
* @param CMD 命令
* @return 字符串结果
*/
private static String runCommand(String CMD) {
StringBuilder info = new StringBuilder();
try {
Process pos = Runtime.getRuntime().exec(CMD);
pos.waitFor();
InputStreamReader isr = new InputStreamReader(pos.getInputStream());
LineNumberReader lnr = new LineNumberReader(isr);
String line;
while ((line = lnr.readLine()) != null) {
info.append(line).append("\n");
}
} catch (Exception e) {
info = new StringBuilder(e.toString());
}
return info.toString();
}
//上面的方法同样只能支持单挑命令的执行,复合命令执行不出结果
添加依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.12</version>
</dependency>
/**
* @author Lazar
* @description : 远程执行命令工具
* @date 2022/1/20 16:22
**/
public static final String getConnect(String sshHost, String sshUser, String sshPass, String cmd) {
Session session = JschUtil.getSession(sshHost, PORT, sshUser, sshPass);
String exec = JschUtil.exec(session, cmd, CharsetUtil.CHARSET_UTF_8);
JschUtil.close(session);
return exec;
}
下面这个方法可以远程执行复合命令,返回执行后的信息
例如
iostat -x | awk -F ' ' '$14>0' | awk '{print $14}' 该命令统计磁盘io的占用情况
//返回结果单位是1/10000
public static long getDiskIoRatio() {
log.info("主机磁盘io信息");
double total = 0;
String num;
try {
String resultInfo = getConnect(IP, USER, PASSWD, ioCmdStr);
log.info("磁盘信息统计结果:{}", resultInfo);
String[] split = resultInfo.split("\n");
List<String> list = Arrays.asList(split);
log.info("统计数组:{}", JSONObject.toJSON(list));
double[] toArray = list.stream().mapToDouble(s -> {
return Double.parseDouble(s);
}).toArray();
total = Arrays.stream(toArray).sum();
} catch (NumberFormatException e) {
total = 0;
}
log.info("使用率: " + total + "%");
return Math.round(total * 10000);
}