centos 监控
1.pom.xml引入

<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
2.java代码

package com.ruoyi.project.system.learn.controller; import ch.ethz.ssh2.ChannelCondition; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class SSHClient { private String ip; private String username; private String password; private String charset = Charset.defaultCharset().toString(); private static final int TIME_OUT = 1000 * 5 * 60; private Connection conn; public SSHClient(String ip, String username, String password) { this.ip = ip; this.username = username; this.password = password; } /** * 登录指远程服务器 * @return * @throws IOException */ private boolean login() throws IOException { conn = new Connection(ip); conn.connect(); return conn.authenticateWithPassword(username, password); } public int exec(String shell) { int ret = -1; try { if (login()) { Session session = conn.openSession(); session.execCommand(shell); session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); ret = session.getExitStatus(); // 获得标准输出流 InputStream is = new StreamGobbler(session.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> result = new ArrayList<>(); for (String line = brs.readLine(); line != null; line = brs.readLine()) { System.out.println(line); } } else { throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略 } }catch(Exception e){ e.printStackTrace(); } finally { if (conn != null) { conn.close(); } } return ret; } public static void main(String[] args){ try { SSHClient sshClient = new SSHClient("IP地址", "用户名", "密码"); sshClient.exec("/root/free.sh"); //脚本文件 } catch (Exception e) { e.printStackTrace(); } } }
3.脚本文件free.sh,赋予权限:chmod +x free.sh

# FNR = 行, print = 列 #内存 MEM_USED=$(free | awk 'FNR == 2 {print $3}') MEM_TOTAL=$(free | awk 'FNR == 2 {print $2}') echo $MEM_TOTAL $MEM_USED #磁盘使用率 DISK_USAGE=$(df -h | awk 'FNR == 6 {sub(/%/, ""); print $5}') echo $DISK_USAGE #查看java进程cpu使用率 echo $(top -bn 1 | grep "java" | awk '{print $9}') #IO iowait=`vmstat |awk '{if(NR==3) print $16}'` echo ${iowait} #查看RuoYi.jar进程ID id=`ps -ef | grep RuoYi.jar | grep -v grep | awk '{print $2}'` echo $id
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术