Java获取服务器CPU、内存、磁盘信息

最近又有一个项目要加上系统监控,需要查询服务器的CPU、内存等系统信息以及系统服务组件的状态,分享一下最简单的系统信息获取方法,思想是用Java的runtime类执行shell命令进行查询。

相关shell命令

## 查询CPU使用情况
top -b -n 1 | awk '/^(%)Cpu/{t1=$2+$4}/^CPU/{t2=$2+$4}END{print t1+t2}'

## 查询内存
free -m | awk 'NR==2{printf "%f\n",$3*100/$2}'	

## 查询磁盘使用情况
df -h  |grep /dev/mapper |awk '{print $5}'

附一个工具类:

package com.snow.shell.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class CommandUtil {

    public static final Logger logger = LoggerFactory.getLogger(CommandUtil.class);

    public static String getCommandResponse(String[] commands){
        StringBuilder strBuilder =new StringBuilder();
        try {
            Runtime runtime = Runtime.getRuntime();
            logger.info(String.format("开始执行shell命令:%s", Arrays.toString(commands)));
            Process exec = runtime.exec(commands);
            exec.waitFor();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(exec.getErrorStream()));

            String line=null;
            while ((line=bufferedReader.readLine())!=null){
                if(!StringUtils.isEmpty(line)){
                    strBuilder.append(line)
                            .append("\n");
                }
            }

            while ((line=errorBufferedReader.readLine())!=null){
                if(!StringUtils.isEmpty(line)){
                    strBuilder.append(line)
                            .append("\n");
                }
            }
        }catch (Exception e){
            logger.error("执行shell命令发生错误",e);
            return "error";
        }
        return strBuilder.toString();
    }


    public static void executeCommand(String[] commands){
        try {
            Runtime runtime = Runtime.getRuntime();
            logger.info(String.format("开始执行shell命令:%s", Arrays.toString(commands)));
            Process exec = runtime.exec(commands);
            exec.waitFor();
        }catch (Exception e){
            logger.error("执行shell命令发生错误",e);
        }
    }
}

使用示例:

 String[] commands = {"/bin/sh", "-c", "cat /etc/hosts"};
 String commandResponse = CommandUtil.getCommandResponse(commands);
 System.out.println("commandResponse = " + commandResponse);
  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 OSHI(Open System Hardware Information)这个 Java 库来获取系统硬件信息,包括 CPU内存磁盘等状态信息。下面是一个简单的示例代码,可以根据 IP 地址获取 Linux 服务器CPU内存磁盘等详细信息: ```java import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.FormatUtil; import java.net.InetAddress; import java.net.UnknownHostException; public class SystemInfoDemo { public static void main(String[] args) throws UnknownHostException { String ipAddress = "192.168.0.1"; // Linux 服务器的 IP 地址 // 根据 IP 地址获取 InetAddress 对象 InetAddress inetAddress = InetAddress.getByName(ipAddress); // 创建 SystemInfo 对象 SystemInfo systemInfo = new SystemInfo(inetAddress); // 获取 HardwareAbstractionLayer 对象 HardwareAbstractionLayer hardware = systemInfo.getHardware(); // 获取 CentralProcessor 对象 CentralProcessor processor = hardware.getProcessor(); // 获取 GlobalMemory 对象 GlobalMemory memory = hardware.getMemory(); // 获取 OperatingSystem 对象 OperatingSystem os = systemInfo.getOperatingSystem(); // 获取 FileSystem 对象 FileSystem fileSystem = os.getFileSystem(); // 输出 CPU 信息 System.out.println("CPU: " + processor.getPhysicalProcessorCount() + " cores"); System.out.println("CPU load: " + processor.getSystemCpuLoad() * 100 + "%"); // 输出内存信息 System.out.println("Memory: " + FormatUtil.formatBytes(memory.getTotal()) + " total"); // 输出磁盘信息 OSFileStore[] fileStores = fileSystem.getFileStores(); for (OSFileStore fileStore : fileStores) { System.out.println("Drive: " + fileStore.getName()); System.out.println("Total space: " + FormatUtil.formatBytes(fileStore.getTotalSpace())); System.out.println("Usable space: " + FormatUtil.formatBytes(fileStore.getUsableSpace())); } } } ``` 需要注意的是,使用 OSHI 库获取系统硬件信息需要在 Linux 服务器上安装并运行 OSHI 的 native 库,具体安装方法可以参考 OSHI 官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值