//單條命令執行,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);
}