远程连接获取Windows/Linux系统信息(内存/CPU...)

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>
/**
 * 获取系统信息
 *
 * @author cwg
 * @version 1.0
 * @date 2025年01月20日
 **/

public class SystemInfoProviderUtil {
    /**
     * 获取系统信息
     * 根据操作系统类型(Windows或Linux),调用相应的系统信息提供者
     *
     * @param host     主机地址
     * @param user     用户名
     * @param password 密码
     * @param port     端口号
     * @return SystemInfo对象,包含系统信息
     */
    public static SystemInfo getSystemInfo(String host, String user, String password, int port, String serverType) {
        SystemInfo systemInfo = new SystemInfo();
        try {
            //不同系统不同命令
            if (serverType.equals("windows")) {
                systemInfo = WindowsSystemInfoProvider(host, user, password, port);
            } else if (serverType.equals("linux")) {
                systemInfo = LinuxSystemInfoProvider(host, user, password, port);
            }
            systemInfo.setType(serverType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return systemInfo;
    }

    /**
     * window系统
     **/
    private static SystemInfo WindowsSystemInfoProvider(String host, String user, String password, int port) throws Exception {
        SystemInfo systemInfo = new SystemInfo();
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        // 执行命令
        String cpuCommand = "wmic cpu get loadpercentage";
        String memoryCommand = "wmic os get freephysicalmemory,totalvisiblememorysize";
        String diskCommand = "wmic logicaldisk get size,freespace,caption";
        String serviceCommand1 = "sc query WinSyncService";
        String serviceCommand2 = "sc query GSessiond";
        String timeCommand = "wmic os get localdatetime";

        // 获取 CPU 使用率
        String cpuUsageResult = executeCommand(session, cpuCommand);
        // 提取所有数字,并将它们转换为整型
        String[] cpuUsageArray = cpuUsageResult.replaceAll("[^\\d]", " ").trim().split("\\s+");
        // 计算平均 CPU 使用率
        int totalCpuUsage = 0;
        int coreCount = cpuUsageArray.length;
        for (String cpuLoad : cpuUsageArray) {
            totalCpuUsage += Integer.parseInt(cpuLoad);
        }
        // 计算平均使用率
        int averageCpuUsage = totalCpuUsage / coreCount;
        // 设置系统 CPU 使用率
        systemInfo.setCpuUsage(averageCpuUsage);
        systemInfo.setCpuCommandResult(cpuUsageResult.replaceAll("[\r\n]", "").trim());

        // 获取内存信息
        String memoryInfo = executeCommand(session, memoryCommand);
        systemInfo.setMemoryCommandResult(memoryInfo.replaceAll("[\r\n]", ""));
        String[] memLines = memoryInfo.split("\n");
        if (memLines.length > 2) {
            String freeMemory = memLines[2].split("\\s+")[0].trim();
            String totalMemory = memLines[2].split("\\s+")[1].trim();
            String usedMemory = String.valueOf(Long.parseLong(totalMemory) - Long.parseLong(freeMemory));
            long usedMemoryPercentage = (long) ((Double.parseDouble(usedMemory) / Double.parseDouble(totalMemory)) * 100);
            systemInfo.setTotalMemory(new BigDecimal(formatMemory(totalMemory).replaceAll("GB", "")));
            systemInfo.setAvailableMemory(new BigDecimal(formatMemory(freeMemory).replaceAll("GB", "")));
            systemInfo.setUsedMemory(new BigDecimal(formatMemory(usedMemory).replaceAll("GB", "")));
            systemInfo.setMemoryUsageRate(usedMemoryPercentage);
        }

        // 初始化存储 C 盘磁盘信息
        long diskUsage = 0;
        BigDecimal diskAvailableMemory = BigDecimal.ZERO;
        // 获取磁盘信息
        StringBuilder diskInfo = new StringBuilder(executeCommand(session, diskCommand));
        systemInfo.setDiskInfoResult(diskInfo.toString().trim());
        String[] lines = diskInfo.toString().split("\n");
        if (lines.length > 1) {
            for (String lineInfo : lines) {
                if (!lineInfo.trim().isEmpty()) {
                    String[] parts = lineInfo.split("\\s+");
                    if (parts.length == 3) {
                        String drive = parts[0]; // 驱动器号
                        String freeSpace = parts[1]; // 可用空间
                        String totalSpace = parts[2]; // 总空间
                        if (!isInteger(freeSpace) || !isInteger(totalSpace)) {
                            diskInfo = new StringBuilder();
                            continue;
                        }
                        long usedSpace = Long.parseLong(totalSpace) - Long.parseLong(freeSpace); // 已使用空间
                        long diskUsagePercentage = (long) ((Double.parseDouble(String.valueOf(usedSpace)) / Double.parseDouble(totalSpace)) * 100);
                        diskInfo.append(String.format("驱动器 %s总空间 = %s, 可用空间 = %s, 已使用空间 = %s, 磁盘使用率 = %d%%\n",
                                drive, formatDiskSpace(totalSpace), formatDiskSpace(freeSpace), formatDiskSpace(String.valueOf(usedSpace)), diskUsagePercentage));
                        if (drive.contains("C")) {
                            diskUsage = diskUsagePercentage;
                            long freeSpaceLong = Long.parseLong(freeSpace);
                            // 设置 C 盘的磁盘使用率和可用空间
                            String freeSpaceDouble = formatDiskSpace(String.valueOf(freeSpaceLong));
                            diskAvailableMemory = new BigDecimal(freeSpaceDouble.replaceAll("GB", ""));
                        }
                    }
                }
            }
        }
        systemInfo.setDiskInfo(diskInfo.toString().trim());
        systemInfo.setDiskUsage(diskUsage);
        systemInfo.setDiskAvailableMemory(diskAvailableMemory);

        // 获取服务状态
        String serviceStatus1 = executeCommand(session, serviceCommand1);
        systemInfo.setWinSyncServiceRunning(serviceStatus1.contains("RUNNING"));
        systemInfo.setWinSyncServiceCommandResult(serviceStatus1.replaceAll("[\r\n]", ""));

        String serviceStatus2 = executeCommand(session, serviceCommand2);
        systemInfo.setGSessionServiceRunning(serviceStatus2.contains("RUNNING"));
        systemInfo.setGSessionServiceCommandResult(serviceStatus2.replaceAll("[\r\n]", ""));

        // 获取当前时间
        String currentTime = executeCommand(session, timeCommand);
        String[] timeParts = currentTime.split("\n");
        if (timeParts.length > 1) {
            String dateTime = timeParts[2].trim();
            currentTime = String.format("%s-%s-%s %s:%s:%s",
                    dateTime.substring(0, 4), dateTime.substring(4, 6), dateTime.substring(6, 8),
                    dateTime.substring(8, 10), dateTime.substring(10, 12), dateTime.substring(12, 14));
            systemInfo.setCurrentTime(currentTime);
        }

        session.disconnect();
        return systemInfo;
    }

    /**
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isInteger(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            // 尝试将字符串转换为 long 类型
            Long.parseLong(str);
            return true;
        } catch (NumberFormatException e) {
            // 如果转换失败,说明该字符串不是有效的 long 类型数字
            return false;
        }
    }

    /**
     * Linux系统
     **/
    private static SystemInfo LinuxSystemInfoProvider(String host, String user, String password, int port) throws Exception {
        SystemInfo systemInfo = new SystemInfo();
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        // 执行命令
        String cpuCommand = "top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'";
        String memoryCommand = "free -m";
        String diskCommand = "df -h";
        String serviceCommand1 = "systemctl status WinSyncService";
        String serviceCommand2 = "systemctl status GSessiond";
        String timeCommand = "date";
        String dfCommand = "df -h /";
        // 获取 CPU 使用率
        String cpuUsageResult = executeCommand(session, cpuCommand);
        double cpuUsage = Double.parseDouble(cpuUsageResult.trim());
        systemInfo.setCpuUsage((int) cpuUsage);
        systemInfo.setCpuCommandResult(cpuUsageResult.trim());


        // 获取内存信息
        String memoryInfo = executeCommand(session, memoryCommand);
        systemInfo.setMemoryCommandResult(memoryInfo.replaceAll("[\r\n]", ""));
        List<String> memLines = splitLines(memoryInfo);
        if (memLines.size() > 1) {
            String[] parts = memLines.get(1).split("\\s+");
            String totalMemory = parts[1];
            String usedMemory = parts[2];
            String freeMemory = parts[3];
            //内存使用率 = (已使用内存 / 总内存) * 100。
            long usedMemoryPercentage = (long) ((Double.parseDouble(usedMemory) / Double.parseDouble(totalMemory)) * 100);
            systemInfo.setTotalMemory(new BigDecimal(formatMemory(totalMemory).replaceAll("GB", "")));
            systemInfo.setAvailableMemory(new BigDecimal(formatMemory(freeMemory).replaceAll("GB", "")));
            systemInfo.setUsedMemory(new BigDecimal(formatMemory(usedMemory).replaceAll("GB", "")));
            systemInfo.setMemoryUsageRate(usedMemoryPercentage);
        }
        // 获取磁盘信息
        StringBuilder diskInfo = new StringBuilder(executeCommand(session, diskCommand));
        //获取磁盘根目录目录信息
        StringBuilder diskInfogen = new StringBuilder(executeCommand(session, dfCommand));
        List<String> strings = splitLines(diskInfogen.toString());
        if (strings.size() > 1) {
            for (int i = 1; i < strings.size(); i++) {
                String lineInfo = strings.get(i);
                String[] parts = lineInfo.split("\\s+");
                if (parts.length >= 5) {
                    String availableSpace = parts[3];
                    systemInfo.setDiskUsage(Long.parseLong(parts[4]));
                    systemInfo.setDiskAvailableMemory(BigDecimal.valueOf(Long.parseLong(availableSpace)));
                    diskInfo.append(String.format("根目录磁盘使用率 = %s, 根目录磁盘可用空间 = %s\n",
                            parts[4], availableSpace));
                }
            }
        }
        systemInfo.setDiskInfoResult(diskInfo.toString().trim());
        List<String> diskLines = splitLines(diskInfo.toString());
        if (diskLines.size() > 1) {
            for (int i = 1; i < diskLines.size(); i++) {
                String lineInfo = diskLines.get(i);
                String[] parts = lineInfo.split("\\s+");
                if (parts.length >= 4) {
                    String drive = parts[0];
                    String totalSpace = parts[1];
                    String usedSpace = parts[2];
                    String availableSpace = parts[3];
                    diskInfo.append(String.format("驱动器 %s总空间 = %s, 可用空间 = %s, 已使用空间 = %s\n",
                            drive, totalSpace, availableSpace, usedSpace));
                }
            }
        }
        systemInfo.setDiskInfo(diskInfo.toString().trim());


        // 获取服务状态
        String serviceStatus1 = executeCommand(session, serviceCommand1);
        systemInfo.setWinSyncServiceRunning(serviceStatus1.contains("active (running)"));
        systemInfo.setWinSyncServiceCommandResult(serviceStatus1.replaceAll("[\r\n]", ""));

        String serviceStatus2 = executeCommand(session, serviceCommand2);
        systemInfo.setGSessionServiceRunning(serviceStatus2.contains("active (running)"));
        systemInfo.setGSessionServiceCommandResult(serviceStatus2.replaceAll("[\r\n]", ""));


        // 获取当前时间
        String currentTime = executeCommand(session, timeCommand);
        systemInfo.setCurrentTime(currentTime.trim());


        session.disconnect();
        return systemInfo;
    }


    // 执行命令的辅助方法
    private static String executeCommand(Session session, String command) throws Exception {
        StringBuilder result = new StringBuilder();
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        channel.setErrStream(System.err);
        InputStream inputStream = channel.getInputStream();
        channel.connect();
        // 使用 UTF-8 编码来读取输入流(根据需要也可以尝试其他编码,如 "GBK")
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line).append("\n");
        }
        channel.disconnect();
        return result.toString();
    }


    // 将磁盘空间从字节转换为 GB
    private static String formatDiskSpace(String spaceInBytes) {
        if (spaceInBytes == null || spaceInBytes.isEmpty()) {
            return "0.00GB";
        }
        try {
            long space = Long.parseLong(spaceInBytes);
            return String.format("%.2fGB", space / (1024.0 * 1024 * 1024)); // 统一返回 GB
        } catch (NumberFormatException e) {
            return spaceInBytes; // 如果解析失败,返回原始值
        }
    }

    // 将内存大小从 KB 转换为 GB
    private static String formatMemory(String memoryInKb) {
        try {
            long memory = Long.parseLong(memoryInKb);
            return String.format("%.2fGB", memory / (1024.0 * 1024)); // 统一返回 GB
        } catch (NumberFormatException e) {
            return memoryInKb; // 如果解析失败,返回原始值
        }
    }

    // 分割多行文本
    private static List<String> splitLines(String input) {
        List<String> lines = new ArrayList<>();
        String[] parts = input.split("\n");
        for (String part : parts) {
            lines.add(part);
        }
        return lines;
    }
}
//实体
@Data
@ToString
public class SystemInfo {
    //cpu使用率
    private int cpuUsage;
    //cpu查询源返回结果
    private String cpuCommandResult;
    //总内存
    private BigDecimal totalMemory;
    //可用内存
    private BigDecimal availableMemory;
    //已使用内存
    private BigDecimal usedMemory;
    //内存使用率
    private long memoryUsageRate;
    //内存查询源返回结果
    private String memoryCommandResult;
    //磁盘信息源返回结果
    private String diskInfoResult;
    //磁盘信息
    private String diskInfo;
    //WinSync Service存活状态
    private boolean winSyncServiceRunning;
    //WinSync Service存活状态源返回结果
    private String winSyncServiceCommandResult;
    //GSessiond 服务 存活状态
    private boolean gSessionServiceRunning;
    //GSessiond 服务 存活状态源返回结果
    private String gSessionServiceCommandResult;
    //当前时间
    private String currentTime;
    //磁盘使用率 windowsC盘或 linux 根目录 /
    private long diskUsage;
    //可用空间
    private BigDecimal diskAvailableMemory;
    //类型 linux || window
    private String type;
}
posted @ 2025-04-25 10:10  小侯学编程  阅读(33)  评论(0)    收藏  举报