JAVA通过oshi获取系统和硬件信息

OSHI 是基于 JNA 的(本地)操作系统和硬件信息库。它不需要安装任何其他额外的本地库,旨在提供一种跨平台的实现来检索系统信息,例如操作系统版本、进程、内存和 CPU 使用率、磁盘和分区、设备、传感器等。

使用 OSHI 可以对应用程序进行监控,可以对应用程序所在的服务器资源进行监控,还可以监控到其他许多指标,如下:

1、计算机系统和固件,底板
2、操作系统和版本 / 内部版本
3、物理(核心)和逻辑(超线程)CPU,处理器组,NUMA 节点
4、系统和每个处理器的负载百分比和滴答计数器
5、CPU 正常运行时间,进程和线程
6、进程正常运行时间,CPU,内存使用率,用户 / 组,命令行
7、已使用 / 可用的物理和虚拟内存
8、挂载的文件系统(类型,可用空间和总空间)
9、磁盘驱动器(型号,序列号,大小)和分区
10、网络接口(IP,带宽输入 / 输出)
11、电池状态(电量百分比,剩余时间,电量使用情况统计信息)
12、连接的显示器(带有 EDID 信息)
13、USB 设备
14、传感器(温度,风扇速度,电压)

支持的平台:

  • Windows
  • Linux
  • macOS
  • UNIX (AIX, FreeBSD, OpenBSD, Solaris)

一、引入jar包

第一个依赖是对这个再次进行封装的一个工具类

第二个依赖 是他的核心依赖

第三个第四个依赖 是为了解决冲突用的

        
            cn.hutool
            hutool-all
            5.8.2
        
        
        
        
            com.github.oshi
            oshi-core
            6.1.5
        
        
        
            net.java.dev.jna
            jna
            5.10.0
        
        
            net.java.dev.jna
            jna-platform
            5.10.0
        

 二、测试工具类

import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import com.alibaba.fastjson.JSONObject;
import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;


public class OshiUtils {

    public static JSONObject recordCpuInfo(){
        CpuInfo cpuInfo = OshiUtil.getCpuInfo();
        CentralProcessor processor = OshiUtil.getProcessor();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cpuTotal",cpuInfo.getToTal());
        jsonObject.put("cpuSys",cpuInfo.getSys());
        jsonObject.put("cpuUser",cpuInfo.getUser());
        jsonObject.put("cpuWait",cpuInfo.getWait());
        jsonObject.put("cpuFree",cpuInfo.getFree());
        jsonObject.put("cpuUsed",cpuInfo.getUsed());
        jsonObject.put("cpuId",processor.getProcessorIdentifier().getProcessorID());
        jsonObject.put("serialNumber",OshiUtil.getSystem().getSerialNumber());
        return jsonObject;
    }



    public static void main(String[] args) {


        SystemInfo systemInfo = new SystemInfo();
        //获取计算机系统,固件,底版--每天执行一次,或者手动执行一次
        System.out.println(OshiUtil.getSystem().getManufacturer());
        System.out.println(OshiUtil.getSystem().getSerialNumber());
        System.out.println(OshiUtil.getSystem().getHardwareUUID());
        //操作系统和版本/内部版本
        System.out.println("====================");
        System.out.println(OshiUtil.getOs());
        //处理器型号,处理器个数,处理器核心数,处理器线程数,标识符,处理器id,供应商
        System.out.println("====================");
        CentralProcessor processor = OshiUtil.getProcessor();
        System.out.println(processor.getProcessorIdentifier().getName());
        System.out.println(processor.getPhysicalPackageCount());
        System.out.println(processor.getPhysicalProcessorCount());
        System.out.println(processor.getLogicalProcessorCount());
        System.out.println(processor.getProcessorIdentifier().getIdentifier());
        System.out.println(processor.getProcessorIdentifier().getProcessorID());
        System.out.println(processor.getProcessorIdentifier().getVendor());

        // 已使用/可用的物理和虚拟内存
        //物理内存的 容量,类型,频率,品牌
        System.out.println("====================");
        GlobalMemory memory = OshiUtil.getMemory();
        List physicalMemoryList = memory.getPhysicalMemory();
        BigDecimal GbDw = new BigDecimal(1024 * 1024 * 1024);
        BigDecimal HzDw = new BigDecimal(1000 * 1000);
        for (PhysicalMemory physicalMemory : physicalMemoryList) {
            System.out.println(physicalMemory.getBankLabel());
            System.out.println(physicalMemory);
            double getCapacity = new BigDecimal(physicalMemory.getCapacity()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(getCapacity);
            System.out.println(physicalMemory.getMemoryType());
            double getClockSpeed = new BigDecimal(physicalMemory.getClockSpeed()).divide(HzDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(getClockSpeed);
            System.out.println(physicalMemory.getManufacturer());
        }
        //交换内存信息
        VirtualMemory virtualMemory = memory.getVirtualMemory();
        double getSwapTotal = new BigDecimal(virtualMemory.getSwapTotal()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
        double getSwapUsed = new BigDecimal(virtualMemory.getSwapUsed()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
        System.out.println(getSwapTotal);
        System.out.println(getSwapUsed);
        //获取使用率
        double getTotal = new BigDecimal(memory.getTotal()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
        double getAvailable = new BigDecimal(memory.getAvailable()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
        System.out.println(getTotal);
        System.out.println(getAvailable);
        //挂载的文件系统(类型,可用空间和总空间)
        System.out.println("====================");
        FileSystem fileSystem = OshiUtil.getOs().getFileSystem();
        List fileStores = fileSystem.getFileStores();
        // 名字,总空间,可用空间,空闲空间,mount,类型,标签,
        for (OSFileStore fileStore : fileStores) {
            System.out.println(fileStore.getName());
            double getTotalSpace = new BigDecimal(fileStore.getTotalSpace()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(getTotalSpace);
            double getUsableSpace = new BigDecimal(fileStore.getUsableSpace()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(getUsableSpace);
            double getFreeSpace = new BigDecimal(fileStore.getFreeSpace()).divide(GbDw).setScale(2, RoundingMode.HALF_UP).doubleValue();
            System.out.println(getFreeSpace);
            System.out.println(fileStore.getMount());
            System.out.println(fileStore.getType());
            System.out.println(fileStore.getLabel());
            System.out.println("----------------------------------");
        }
        System.out.println("====================");
        //网络接口(IP,带宽输入/输出)
        //名称,接收的字节数,发送的字节数,ipv4地址,ipv6地址,接受包大小,发送包大小,显示名称,别名,操作状态,mac地址,mtu,速度
        List networkIFs = OshiUtil.getNetworkIFs();
        for (NetworkIF networkIF : networkIFs) {
            System.out.println(networkIF.getName());

            System.out.println(networkIF.getBytesRecv());
            System.out.println(networkIF.getBytesSent());

            System.out.println( Arrays.toString(networkIF.getIPv4addr()) );
            System.out.println( Arrays.toString(networkIF.getIPv6addr()) );

            System.out.println(networkIF.getPacketsRecv());
            System.out.println(networkIF.getPacketsSent());

            System.out.println(networkIF.getDisplayName());
            System.out.println(networkIF.getIfAlias());
            System.out.println(networkIF.getIfOperStatus());

            System.out.println(networkIF.getMacaddr());

            System.out.println(networkIF.getMTU());

            System.out.println(networkIF.getSpeed());
            System.out.println("-----------------------------------");
        }
        System.out.println("====================");
        //电池状态(电量百分比,剩余时间,电量使用情况统计信息)
        List powerSources = OshiUtil.getHardware().getPowerSources();
        //名称,安培,制造商,容量单位,当前容量,循环次数,初始容量,设备名字,制造日期,电池当前最大容量,电池使用率,电量剩余百分比,当前温度,电压
        for (PowerSource powerSource : powerSources) {

            System.out.println(powerSource.getName());
            System.out.println(powerSource.getAmperage());
            System.out.println(powerSource.getManufacturer());
            System.out.println(powerSource.getCapacityUnits());
            System.out.println(powerSource.getCurrentCapacity());
            System.out.println(powerSource.getCycleCount());
            System.out.println(powerSource.getDesignCapacity());
            System.out.println(powerSource.getDeviceName());
            System.out.println(powerSource.getManufactureDate());
            System.out.println(powerSource.getMaxCapacity());
            System.out.println(powerSource.getPowerUsageRate());
            System.out.println(powerSource.getRemainingCapacityPercent());
//            System.out.println(powerSource.getTemperature());
            System.out.println(powerSource.getVoltage());
        }
        //传感器(温度,风扇速度,电压)
        Sensors sensors = OshiUtil.getSensors();
        //处理器温度
        System.out.println(sensors.getCpuTemperature());
        //处理器电压
        System.out.println(sensors.getCpuVoltage());
        //风扇转速
        System.out.println(Arrays.toString(sensors.getFanSpeeds()));
//        System.out.println(cpuInfo.getCpuModel());
        SystemInfo si = new SystemInfo();
        System.out.println(si.getHardware().getSensors().getCpuTemperature());
    }
}

三、mac地址+序列号+处理器ID组成字符串,加密为16位的字符

    @Test
    public void oshiDemo() {
        List netwoeks = OshiUtil.getHardware().getNetworkIFs();
        StringBuilder macAddress = new StringBuilder();
        List IpList = new ArrayList<>();

        System.out.println("(网络接口)Network interfaces:");
        for (NetworkIF net : netwoeks) {
            macAddress.append(net.getMacaddr());
            String temp = StrUtil.join(",", (Object) net.getIPv4addr());
            if (StringUtils.isNoneBlank(temp)) {
                IpList.add(temp);
            }
        }

        ComputerSystem system = OshiUtil.getSystem();
        // 序列号
        String serialNumber = system.getSerialNumber();
        // 处理器ID
        String processorID = OshiUtil.getProcessor().getProcessorIdentifier().getProcessorID();
        // mac地址+序列号+处理器ID组成字符串
        String l = macAddress + serialNumber + processorID;
        //加密为16位的字符
        System.out.println(SM4.SM4Mac(FAST_MAC_KEY, l.getBytes()));
    }

    public static byte[] FAST_MAC_KEY = HexUtil.decodeHex("BF8F83A656BD75925379384E454DD174");

 SM4工具类:

    public static String SM4Mac(byte[] keyValue, byte[] data) {
        //把报文以8字节分组,最后一组不足8字节补0,
        int datalen = data.length;
        //不足16位不足16位
        datalen += (16 - datalen % 16) % 16;
        byte[] secdata = new byte[datalen];
        System.arraycopy(data, 0, secdata, 0, data.length);
        for (int i = data.length; i < datalen; i++) {
            secdata[i] = 0x00;
        }
        byte[] res = new byte[16];
        byte[] temp = new byte[16];

        /**按每8个字节做异或 **/
        int arrayLen = datalen / 16;
        for (int i = 0; i < arrayLen; i++) {
            for (int j = 0; j < 16; j++) {
                // DESEncrypt0(secdata[i * 8 + j], key1);
                temp[j] = secdata[i * 16 + j];
                temp[j] ^= res[j];
            }
//			SM4.GMSM4(temp, temp.length, keyValue, res, SM4.ENCRYPT);
            res = SM4.encryptData_ECB(temp, keyValue);
        }
        return HexUtil.convertByteArrayToHexStr(res);
    }

    /**
     * SM4_ECB 加密
     *
     * @param plainText
     * @param key
     * @return
     */
    public static byte[] encryptData_ECB(byte[] plainText, byte[] key) {
        try {
            SM4_Context ctx = new SM4_Context(false);
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, key);
            return sm4.sm4_crypt_ecb(ctx, plainText);
        } catch (Exception e) {
            log.error("SM4_ECB 加密异常!", e);
        }
        return null;
    }

16进制转换工具类: 

    /**
     * 将字节数组转换成十六进制字符串
     *
     * @param srcByteArray 字节数组
     * @return 十六进制字符串
     */
    public static String convertByteArrayToHexStr(byte[] srcByteArray) {
        String sTemp = null;
        StringBuffer sOutLine = new StringBuffer();
        byte[] inByte = srcByteArray;
        for (int iSerie = 0; iSerie < inByte.length; iSerie++) {
            // System.out.println("inbyte"+iSerie+inByte[iSerie]);
            if (inByte[iSerie] < 0) {
                sTemp = Integer.toHexString(256 + inByte[iSerie]);
            } else {
                sTemp = Integer.toHexString(inByte[iSerie]);
            }
            if (sTemp.length() < 2) {
                sTemp = "0" + sTemp;
            }
            sTemp = sTemp.toUpperCase();
            sOutLine = sOutLine.append(sTemp);
        }
        return sOutLine.toString();
    }

github地址: 

https://github.com/oshi/oshi

更多输出信息可参考:

java获取系统信息(stringBoot)_Mr_LiYYD的博客-CSDN博客

你可能感兴趣的:(Java实践,java)