# 获取系统信息 (oshi-core)

# 1、maven

<dependency>
   <groupId>com.github.oshi</groupId>
   <artifactId>oshi-core</artifactId>
   <version>3.5.0</version>
</dependency>

# 2、API

对象方法描述
SystemInfogetOperatingSystem()获取操作系统信息,OperatingSystem
getHardware()获取硬件信息,HardwareAbstractionLayer
OperatingSystemgetFamily()获取操作系统名称,例如 Windows
getManufacturer()获取供货商,例如 Microsoft
getVersion()获取操作系统版本信息
getFileSystem()获取系统硬盘信息,FileSystem
getProcesses(int pId, OperatingSystem.ProcessSort var2)通过 进程 id 获取进程信息,并设置排序方式,OSProcess []
getProcess(int pId)通过 进程 id 获取一个进程信息,OSProcess
getProcesses(Collection<Integer> pId)获取多个进程信息,List<OSProcess>
getChildProcesses(int var1, int var2, OperatingSystem.ProcessSort var3)获取子进程,OSProcess []
getProcessId()获取进程 id
getProcessCount()获取进程数量
getThreadCount()获取线程数
getNetworkParams()获取网络相关参数,NetworkParams
HardwareAbstractionLayergetComputerSystem()获取计算机系统信息,ComputerSystem
getProcessor()获取处理器信息,CentralProcessor
getMemory()获取内存信息,GlobalMemory
getPowerSources()获取电源信息,PowerSource
getDiskStores()获取硬件磁盘信息,HWDiskStore
getNetworkIFs()获取网络信息,NetworkIF
getDisplays()获取显示信息,Display
getSensors()获取传感器信息,Sensors
getUsbDevices(boolean var1)获取 USB 设备信息,UsbDevice
OperatingSystemVersiongetBuildNumber()获取内部编号
getCodeName()代码名称
getVersion()获取版本
FileSystemgetMaxFileDescriptors()获取最大文件描述符
getOpenFileDescriptors()获取打开文件描述符
getFileStores()获取盘符相关信息
OSProcessgetName()进程程序名称
getPath()进程程序所在位置
getCommandLine()获取命令行
getCurrentWorkingDirectory()获取当前工作目录
getUser()获取用户信息
getUserID()获取用户 id
getGroup()获取组信息
getGroupID()获取组 id
getState()状态
getProcessID()获取进程 id
getParentProcessID()获取父进程 id
getThreadCount()获取线程数
getPriority()优先级
getVirtualSize()虚拟大小
getResidentSetSize()实际使用物理内存
getKernelTime()内核时间
getUserTime()用户时间
getUpTime()正常运行时间
getStartTime()开始时间
getBytesRead()读取字节
getBytesWritten()写入字节
getOpenFiles()打开文件数量
NetworkParamsgetDnsServers()获取域名地址
getHostName()获取主机名
getDomainName()获取域名
getIpv4DefaultGateway()获取默认 Ipv4
getIpv6DefaultGateway()获取默认 Ipv6
OSFileStoregetName()磁盘名称
getVolume()文件集
getLogicalVolume()合理的文件集
getMount()盘符
getDescription()描述
getType()类型
getUUID()磁盘 UUID
getUsableSpace()可用空间
getTotalSpace()总空间
ComputerSystemgetManufacturer()获取制造商
getModel()获取型号
getSerialNumber()获取序列号
getFirmware()获取固件信息,Firmware
getBaseboard()获取外壳信息,Baseboard
FirmwaregetManufacturer()获取制造商信息
getName()获取名称
getDescription()获取描述信息
getVersion()获取版本
getReleaseDate()获取发布时间
BaseboardgetModel()获取型号
getVersion()获取版本信息
getSerialNumber()获取序列号
CentralProcessorgetVendor()获取供应商
getName()获取 cpu 名称
getVendorFreq()获取供应商频率
getProcessorID()获取处理器 id
getIdentifier()获取标识符
isCpu64bit()判断 cpu 是否为 64 位的
getStepping()获取 cpu 步进
getModel()获取型号
getFamily()获取家族
getSystemCpuLoadBetweenTicks()获取 cpu 负载间隔刻度
getSystemCpuLoadTicks()获取 cpu 负载刻度
getSystemCpuLoad()获取 cpu 负载
getSystemLoadAverage()获取 cpu 平均负载
getSystemLoadAverage(int var1)获取 cpu 平均负载
getProcessorCpuLoadBetweenTicks()获取处理器 cpu 负载间隔刻度
getProcessorCpuLoadTicks()获取处理器 cpu 负载刻度
getSystemUptime()获取正常运行时间
getLogicalProcessorCount()获取逻辑处理器数量
getPhysicalProcessorCount()获取物理处理器数量
getPhysicalPackageCount()获取物理包装数量
getContextSwitches()获取上下文切换数量
getInterrupts()获取中断
GlobalMemorygetTotal()获取总内存
getAvailable()获取可用系统运行内存
getSwapTotal()获取可用虚拟总内存
getSwapUsed()获取已用虚拟总内存
PowerSourcegetName()获取名称
getRemainingCapacity()获取剩余容量
getTimeRemaining()获取剩余时间
HWDiskStoregetName()获取名称
getModel()获取型号
getSerial()获取序列号
getSize()获取大小
getReads()(读长)是高通量测序中一个反应获得的测序序列
getReadBytes()读取字节
getWrites()写长
getWriteBytes()写入字节
getTransferTime()获取转移时间
getPartitions()获取分区,HWPartition
getTimeStamp()获取时间戳
NetworkIFgetName()获取名称
getDisplayName()获取显示名称
getMTU()获取最大传输单元
getMacaddr()获取 MAC 地址
getIPv4addr()获取 IPv4
getIPv6addr()获取 IPv6
getBytesRecv()获取接收字节数
getBytesSent()获取发送字节数
getPacketsRecv()获取接收数据包
getPacketsSent()获取发送数据包
getInErrors()是否可达,正常 0
getOutErrors()响应错误,无错误 0
getSpeed()获取速率
getTimeStamp()获取时间错
DisplaygetEdid()中文名称扩展显示器识别数据
SensorsgetCpuTemperature()获取 CPU 温度
getFanSpeeds()获取风扇速度
getCpuVoltage()获取 CPU 电压
UsbDevicegetName()获取名称
getVendor()获取供应商
getVendorId()获取供应商 id
getProductId()获取商品 id
getSerialNumber()获取序列号
getConnectedDevices()获取连接设备

示例代码

package com.zp.utils;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.Util;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.Properties;
 
/**
* 系统消息工具类
*
**/
public class SystemInfoUtils {
    private static final int OSHI_WAIT_SECOND = 1000;
    private static SystemInfo systemInfo = new SystemInfo();
    private static HardwareAbstractionLayer hardware = systemInfo.getHardware();
    private static OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
 
    public static JSONObject getCpuInfo() {
        JSONObject cpuInfo = new JSONObject();
        CentralProcessor processor = hardware.getProcessor();
        // CPU 信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        //cpu 核数
        cpuInfo.put("cpuNum", processor.getLogicalProcessorCount());
        //cpu 系统使用率
        cpuInfo.put("cSys", new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        //cpu 用户使用率
        cpuInfo.put("user", new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        //cpu 当前等待率
        cpuInfo.put("iowait", new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        //cpu 当前使用率
        cpuInfo.put("idle", new DecimalFormat("#.##%").format(1.0 - (idle * 1.0 / totalCpu)));
        return cpuInfo;
    }
 
    /**
     * 系统 jvm 信息
     */
    public static JSONObject getJvmInfo() {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        Runtime runtime = Runtime.getRuntime();
        long jvmTotalMemoryByte = runtime.totalMemory();
        long freeMemoryByte = runtime.freeMemory();
        //jvm 总内存
        cpuInfo.put("total", formatByte(runtime.totalMemory()));
        // 空闲空间
        cpuInfo.put("free", formatByte(runtime.freeMemory()));
        //jvm 最大可申请
        cpuInfo.put("max", formatByte(runtime.maxMemory()));
        //vm 已使用内存
        cpuInfo.put("user", formatByte(jvmTotalMemoryByte - freeMemoryByte));
        //jvm 内存使用率
        cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((jvmTotalMemoryByte - freeMemoryByte) * 1.0 / jvmTotalMemoryByte));
        //jdk 版本
        cpuInfo.put("jdkVersion", props.getProperty("java.version"));
        //jdk 路径
        cpuInfo.put("jdkHome", props.getProperty("java.home"));
        return cpuInfo;
    }
 
    /**
     * 系统内存信息
     */
    public static JSONObject getMemInfo() {
        JSONObject cpuInfo = new JSONObject();
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        // 总内存
        long totalByte = memory.getTotal();
        // 剩余
        long acaliableByte = memory.getAvailable();
        // 总内存
        cpuInfo.put("total", formatByte(totalByte));
        // 使用
        cpuInfo.put("used", formatByte(totalByte - acaliableByte));
        // 剩余内存
        cpuInfo.put("free", formatByte(acaliableByte));
        // 使用率
        cpuInfo.put("usageRate", new DecimalFormat("#.##%").format((totalByte - acaliableByte) * 1.0 / totalByte));
        return cpuInfo;
    }
 
    /**
     * 系统盘符信息
     */
    public static JSONArray getSysFileInfo() {
        JSONObject cpuInfo;
        JSONArray sysFiles = new JSONArray();
        FileSystem fileSystem = operatingSystem.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            cpuInfo = new JSONObject();
            // 盘符路径
            cpuInfo.put("dirName", fs.getMount());
            // 盘符类型
            cpuInfo.put("sysTypeName", fs.getType());
            // 文件类型
            cpuInfo.put("typeName", fs.getName());
            // 总大小
            cpuInfo.put("total", formatByte(fs.getTotalSpace()));
            // 剩余大小
            cpuInfo.put("free", formatByte(fs.getUsableSpace()));
            // 已经使用量
            cpuInfo.put("used", formatByte(fs.getTotalSpace() - fs.getUsableSpace()));
            if (fs.getTotalSpace() == 0) {
                // 资源的使用率
                cpuInfo.put("usage", 0);
            } else {
                cpuInfo.put("usage",new DecimalFormat("#.##%").format((fs.getTotalSpace() - fs.getUsableSpace()) * 1.0 / fs.getTotalSpace()));
            }
            sysFiles.add(cpuInfo);
        }
        return sysFiles;
    }
 
    /**
     * 系统信息
     */
    public static JSONObject getSysInfo() throws UnknownHostException {
        JSONObject cpuInfo = new JSONObject();
        Properties props = System.getProperties();
        // 操作系统名
        cpuInfo.put("osName", props.getProperty("os.name"));
        // 系统架构
        cpuInfo.put("osArch", props.getProperty("os.arch"));
        // 服务器名称
        cpuInfo.put("computerName", InetAddress.getLocalHost().getHostName());
        // 服务器 Ip
        cpuInfo.put("computerIp", InetAddress.getLocalHost().getHostAddress());
        // 项目路径
        cpuInfo.put("userDir", props.getProperty("user.dir"));
        return cpuInfo;
    }
 
    /**
     * 所有系统信息
     */
    public static JSONObject getInfo() throws UnknownHostException {
        JSONObject info = new JSONObject();
        info.put("cpuInfo", getCpuInfo());
        info.put("jvmInfo", getJvmInfo());
        info.put("memInfo", getMemInfo());
        info.put("sysInfo", getSysInfo());
        info.put("sysFileInfo", getSysFileInfo());
        return info;
    }
 
    /**
     * 单位转换
     */
    private static String formatByte(long byteNumber) {
        // 换算单位
        double FORMAT = 1024.0;
        double kbNumber = byteNumber / FORMAT;
        if (kbNumber < FORMAT) {
            return new DecimalFormat("#.##KB").format(kbNumber);
        }
        double mbNumber = kbNumber / FORMAT;
        if (mbNumber < FORMAT) {
            return new DecimalFormat("#.##MB").format(mbNumber);
        }
        double gbNumber = mbNumber / FORMAT;
        if (gbNumber < FORMAT) {
            return new DecimalFormat("#.##GB").format(gbNumber);
        }
        double tbNumber = gbNumber / FORMAT;
        return new DecimalFormat("#.##TB").format(tbNumber);
    }
}