下面的代码直接打包带走使用
1、pom文件依赖
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.55</version> <!-- 请根据实际情况检查最新版本 --></dependency>
2、代码
package com.xffy.order.controller;import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;public class LinuxServerInfo {public static void main(String[] args) {String host = "10.15.111.15";int port = 22;String username = "zhang";String password = "123456";try {// 创建JSch对象JSch jsch = new JSch();// 创建会话Session session = jsch.getSession(username, host, port);session.setConfig("StrictHostKeyChecking", "no");session.setPassword(password);// 连接session.connect();// 获取服务器信息String serverName = executeCommand(session, "hostname");String internalIP = executeCommand(session, "hostname -I | awk '{print $1}'");String cpuUsage = executeCommand(session, "top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'");String memoryUsage = executeCommand(session, "free | awk 'NR==2 {print $3/$2*100}'");String diskUsage = executeCommand(session, "df -h | awk '$NF==\"/\"{print $5}'");double jvmUsage = getJVMUsage();String jvmUsageStr = String.format("%.0f", jvmUsage) + "%";// 打印结果System.out.println("Server Name: " + serverName);System.out.println("Internal IP: " + internalIP);System.out.println("CPU Usage: " + cpuUsage + "%");System.out.println("Memory Usage: " + memoryUsage + "%");System.out.println("Disk Usage: " + diskUsage);System.out.println("JVM Usage: " + jvmUsageStr);// 关闭会话session.disconnect();} catch (JSchException e) {e.printStackTrace();}}// 执行Shell命令并获取输出private static String executeCommand(Session session, String command) throws JSchException {StringBuilder output = new StringBuilder();try {// 创建通道Channel channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);// 获取输入流InputStream inputStream = channel.getInputStream();// 连接通道channel.connect();// 读取命令输出BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));String line;while ((line = reader.readLine()) != null) {output.append(line).append("\n");}// 关闭通道channel.disconnect();} catch (IOException e) {e.printStackTrace();}return output.toString().trim();}// 获取JVM使用率private static double getJVMUsage() {Runtime runtime = Runtime.getRuntime();double totalMemory = runtime.totalMemory();double freeMemory = runtime.freeMemory();double maxMemory = runtime.maxMemory();double jvmUsage = ((totalMemory - freeMemory) / maxMemory) * 100;return jvmUsage;}
}