OSHI介绍:
OSHI是一个基于JNA的免费的本地操作系统和Java的硬件信息库。它不需要安装任何额外的本机库,旨在提供跨平台的实现来检索系统信息,如操作系统版本、进程、内存和CPU使用情况、磁盘和分区、设备、传感器等。
github地址:https://github.com/oshi/oshi
代码示例:
maven引入:
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>5.3.6</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.6.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.6.0</version>
</dependency>
注:oshi-core会自动引入依赖jna和jna-platform,但是如果springboot框架自带的jna版本跟这个jar包需要的版本冲突时,就要手动再引入一次,比如5.3.6的oshi-core,依赖的是5.6.0的jna,而我本地的springboot2.2.1自带的jna时4.5.2的,这样有些api可以用,有些api是有问题的,所以统一了5.6.0的版本,具体依赖版本可以去maven仓库官网查询:
编写OshiUtil工具类
package com.zhaohy.app.utils;
import java.util.Arrays;
import java.util.List;
import oshi.SystemInfo;
import oshi.hardware.Baseboard;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.ComputerSystem;
import oshi.hardware.Display;
import oshi.hardware.Firmware;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HWDiskStore;
import oshi.hardware.HWPartition;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
import oshi.hardware.PowerSource;
import oshi.hardware.Sensors;
import oshi.hardware.UsbDevice;
import oshi.software.os.FileSystem;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSFileStore;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystem.ProcessSort;
import oshi.util.FormatUtil;
import oshi.util.Util;
/**
* OSHI工具类
* @author zhaohy
*
*/
public class OshiUtil {
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
System.out.println("Initializing System...");
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
OperatingSystem os = si.getOperatingSystem();
System.out.println(os);
System.out.println("Checking computer system...");
printComputerSystem(hal.getComputerSystem());
System.out.println("Checking Processor...");
printProcessor(hal.getProcessor());
System.out.println("Checking Memory...");
printMemory(hal.getMemory());
System.out.println("Checking CPU...");
printCpu(hal.getProcessor());
System.out.println("Checking Processes...");
printProcesses(os, hal.getMemory());
System.out.println("Checking Sensors...");
printSensors(hal.getSensors());
System.out.println("Checking Power sources...");
printPowerSources(hal.getPowerSources());
System.out.println("Checking Disks...");
printDisks(hal.getDiskStores());
System.out.println("Checking File System...");
printFileSystem(os.getFileSystem());
System.out.println("Checking Network interfaces...");
printNetworkInterfaces(hal.getNetworkIFs());
System.out.println("Checking Network parameterss...");
printNetworkParameters(os.getNetworkParams());
// hardware: displays
System.out.println("Checking Displays...");
printDisplays(hal.getDisplays());
// hardware: USB devices
//System.out.println("Checking USB Devices...");
//printUsbDevices(hal.getUsbDevices(true));
}
private static void printComputerSystem(final ComputerSystem computerSystem) {
System.out.println("manufacturer: " + computerSystem.getManufacturer());
System.out.println("model: " + computerSystem.getModel());
System.out.println("serialnumber: " + computerSystem.getSerialNumber());
final Firmware firmware = computerSystem.getFirmware();
System.out.println("firmware:");
System.out.println(" manufacturer: " + firmware.getManufacturer());
System.out.println(" name: " + firmware.getName());
System.out.println(" description: " + firmware.getDescription());
System.out.println(" version: " + firmware.getVersion());
// System.out.println(" release date: " + (firmware.getReleaseDate() == null ? "unknown": firmware.getReleaseDate() == null ? "unknown" : FormatUtil.formatDate(firmware.getReleaseDate())));
final Baseboard baseboard = computerSystem.getBaseboard();
System.out.println("baseboard:");
System.out.println(" manufacturer: " + baseboard.getManufacturer());
System.out.println(" model: " + baseboard.getModel());
System.out.println(" version: " + baseboard.getVersion());
System.out.println(" serialnumber: " + baseboard.getSerialNumber());
}
private static void printProcessor(CentralProcessor processor) {
System.out.println(processor);
System.out.println(" " + processor.getPhysicalPackageCount() + " physical CPU package(s)");
System.out.println(" " + processor.getPhysicalProcessorCount() + " physical CPU core(s)");
System.out.println(" " + processor.getLogicalProcessorCount() + " logical CPU(s)");
System.out.println("Identifier: " + processor.getProcessorIdentifier());
System.out.println("ProcessorID: " + processor.getProcessorIdentifier().getProcessorID());
}
private static void printMemory(GlobalMemory memory) {
System.out.println("Memory: " + FormatUtil.formatBytes(memory.getAvailable()) + "/"
+ FormatUtil.formatBytes(memory.getTotal()));
System.out.println("Swap used: " + FormatUtil.formatBytes(memory.getVirtualMemory().getSwapUsed()) + "/"
+ FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal()));
}
private static void printCpu(CentralProcessor processor) {
System.out.println(
"Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());
long[] prevTicks = processor.getSystemCpuLoadTicks();
System.out.println("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));
// Wait a second...
Util.sleep(1000);
long[] ticks = processor.getSystemCpuLoadTicks();
System.out.println("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;
System.out.format(
"User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n",
100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu);
System.out.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100);
//System.out.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100);
double[] loadAverage = processor.getSystemLoadAverage(3);
System.out.println("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))
+ (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))
+ (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));
// per core CPU
// StringBuilder procCpu = new StringBuilder("CPU load per processor:");
// double[] load = processor.getProcessorCpuLoadBetweenTicks();
// for (double avg : load) {
// procCpu.append(String.format(" %.1f%%", avg * 100));
// }
// System.out.println(procCpu.toString());
}
private static void printProcesses(OperatingSystem os, GlobalMemory memory) {
System.out.println("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
// Sort by highest CPU
List<OSProcess> procs = os.getProcesses(5, ProcessSort.CPU);
System.out.println(" PID %CPU %MEM VSZ RSS Name");
for (int i = 0; i < procs.size() && i < 5; i++) {
OSProcess p = procs.get(i);
System.out.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),
100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
FormatUtil.formatBytes(p.getResidentSetSize()), p.getName());
}
}
private static void printSensors(Sensors sensors) {
System.out.println("Sensors:");
System.out.format(" CPU Temperature: %.1f°C%n", sensors.getCpuTemperature());
System.out.println(" Fan Speeds: " + Arrays.toString(sensors.getFanSpeeds()));
System.out.format(" CPU Voltage: %.1fV%n", sensors.getCpuVoltage());
}
private static void printPowerSources(List<PowerSource> list) {
StringBuilder sb = new StringBuilder("Power: ");
if (list.size() == 0) {
sb.append("Unknown");
} else {
double timeRemaining = list.get(0).getTimeRemainingInstant();
if (timeRemaining < -1d) {
sb.append("Charging");
} else if (timeRemaining < 0d) {
sb.append("Calculating time remaining");
} else {
sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600),
(int) (timeRemaining / 60) % 60));
}
}
for (PowerSource pSource : list) {
sb.append(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacityPercent() * 100d));
}
System.out.println(sb.toString());
}
private static void printDisks(List<HWDiskStore> list) {
System.out.println("Disks:");
for (HWDiskStore disk : list) {
boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;
System.out.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",
disk.getName(), disk.getModel(), disk.getSerial(),
disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",
readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",
readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",
readwrite ? disk.getTransferTime() : "?");
List<HWPartition> partitions = disk.getPartitions();
if (partitions == null) {
// TODO Remove when all OS's implemented
continue;
}
for (HWPartition part : partitions) {
System.out.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),
part.getName(), part.getType(), part.getMajor(), part.getMinor(),
FormatUtil.formatBytesDecimal(part.getSize()),
part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint());
}
}
}
private static void printFileSystem(FileSystem fileSystem) {
System.out.println("File System:");
System.out.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),
fileSystem.getMaxFileDescriptors());
List<OSFileStore> fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long usable = fs.getUsableSpace();
long total = fs.getTotalSpace();
System.out.format(
" %s (%s) [%s] %s of %s free (%.1f%%) is %s "
+ (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")
+ " and is mounted at %s%n",
fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
fs.getVolume(), fs.getLogicalVolume(), fs.getMount());
}
}
private static void printNetworkInterfaces(List<NetworkIF> list) {
System.out.println("Network interfaces:");
for (NetworkIF net : list) {
System.out.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName());
System.out.format(" MAC Address: %s %n", net.getMacaddr());
System.out.format(" MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps"));
System.out.format(" IPv4: %s %n", Arrays.toString(net.getIPv4addr()));
System.out.format(" IPv6: %s %n", Arrays.toString(net.getIPv6addr()));
boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0
|| net.getPacketsSent() > 0;
System.out.format(" Traffic: received %s/%s%s; transmitted %s/%s%s %n",
hasData ? net.getPacketsRecv() + " packets" : "?",
hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",
hasData ? " (" + net.getInErrors() + " err)" : "",
hasData ? net.getPacketsSent() + " packets" : "?",
hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",
hasData ? " (" + net.getOutErrors() + " err)" : "");
}
}
private static void printNetworkParameters(NetworkParams networkParams) {
System.out.println("Network parameters:");
System.out.format(" Host name: %s%n", networkParams.getHostName());
System.out.format(" Domain name: %s%n", networkParams.getDomainName());
System.out.format(" DNS servers: %s%n", Arrays.toString(networkParams.getDnsServers()));
System.out.format(" IPv4 Gateway: %s%n", networkParams.getIpv4DefaultGateway());
System.out.format(" IPv6 Gateway: %s%n", networkParams.getIpv6DefaultGateway());
}
private static void printDisplays(List<Display> list) {
System.out.println("Displays:");
int i = 0;
for (Display display : list) {
System.out.println(" Display " + i + ":");
System.out.println(display.toString());
i++;
}
}
private static void printUsbDevices(List<UsbDevice> list) {
System.out.println("USB Devices:");
for (UsbDevice usbDevice : list) {
System.out.println(usbDevice.toString());
}
}
}
main方法运行结果如下:
Initializing System...
GNU/Linux Ubuntu 20.04.1 LTS (Focal Fossa) build 5.4.0-58-generic
Checking computer system...
manufacturer: ASUSTeK COMPUTER INC.
model: VC66-C (version: To be filled by O.E.M.)
serialnumber: unknown
firmware:
manufacturer: unknown
name: unknown
description: dmi:bvnASUSTeKCOMPUTERINC.:bvr0403:bd05/23/2018:svnASUSTeKCOMPUTERINC.:pnVC66-C:pvrTobefilledbyO.E.M.:rvnASUSTeKCOMPUTERINC.:rnVC66-C:rvrTobefilledbyO.E.M.:cvnDefaultstring:ct3:cvrDefaultstring:
version: 0403
baseboard:
manufacturer: ASUSTeK COMPUTER INC.
model: VC66-C
version: To be filled by O.E.M.
serialnumber: unknown
Checking Processor...
Intel(R) Core(TM) i5-8400 CPU @ 2.80GHz
1 physical CPU package(s)
6 physical CPU core(s)
6 logical CPU(s)
Identifier: Intel64 Family 6 Model 158 Stepping 10
ProcessorID: AFC1FBFF009006EA
Microarchitecture: Coffee Lake
1 physical CPU package(s)
6 physical CPU core(s)
6 logical CPU(s)
Identifier: Intel64 Family 6 Model 158 Stepping 10
ProcessorID: AFC1FBFF009006EA
Checking Memory...
Memory: 8.0 GiB/15.5 GiB
Swap used: 0 bytes/2.0 GiB
Checking CPU...
Context Switches/Interrupts: 103493568 / 36712695
CPU, IOWait, and IRQ ticks @ 0 sec:[11928130, 25380, 2664520, 90173610, 38790, 0, 1442860, 0]
CPU, IOWait, and IRQ ticks @ 1 sec:[11928700, 25380, 2664650, 90178980, 38790, 0, 1442960, 0]
User: 9.2% Nice: 0.0% System: 2.1% Idle: 87.0% IOwait: 0.0% IRQ: 0.0% SoftIRQ: 1.6% Steal: 0.0%
CPU load: 13.0% (counting ticks)
CPU load averages: 5.94 5.91 5.90
Checking Processes...
Processes: 340, Threads: 1268
PID %CPU %MEM VSZ RSS Name
24882 72.0 0.8 6.5 GiB 122.3 MiB java
12342 23.7 13.4 88.6 GiB 2.1 GiB java
5117 13.7 1.3 798.2 MiB 208.6 MiB chrome
2082 11.0 3.0 5.4 GiB 469.9 MiB gnome-shell
1913 9.2 0.5 895.5 MiB 86.7 MiB Xorg
Checking Sensors...
Sensors:
CPU Temperature: 59.0°C
Fan Speeds: []
CPU Voltage: 0.0V
Checking Power sources...
Power: Unknown
Checking Disks...
Disks:
/dev/nvme0n1: (model: PLEXTOR PX-512M9PeG - S/N: P02930105718) size: 512.1 GB, reads: 144985 (3.7 GiB), writes: 145229 (4.2 GiB), xfer: 122948 ms
|-- /dev/nvme0n1p1: /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/nvme/nvme0/nvme0n1/nvme0n1p1 (vfat) Maj:Min=259:1, size: 103.8 MB @ /boot/efi
|-- /dev/nvme0n1p2: /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/nvme/nvme0/nvme0n1/nvme0n1p2 (partition) Maj:Min=259:2, size: 134.2 MB
|-- /dev/nvme0n1p3: /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/nvme/nvme0/nvme0n1/nvme0n1p3 (ntfs) Maj:Min=259:3, size: 82.7 GB
|-- /dev/nvme0n1p4: /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/nvme/nvme0/nvme0n1/nvme0n1p4 (ext4) Maj:Min=259:4, size: 214.7 GB @ /
|-- /dev/nvme0n1p5: /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/nvme/nvme0/nvme0n1/nvme0n1p5 (ext4) Maj:Min=259:5, size: 214.4 GB
Checking File System...
File System:
File Descriptors: 24256/9223372036854775807
/ (Local Disk) [ext4] 74.2 GiB of 195.9 GiB free (37.9%) is /dev/nvme0n1p4 and is mounted at /
/dev/nvme0n1p1 (Local Disk) [vfat] 41.8 MiB of 98.8 MiB free (42.4%) is /dev/nvme0n1p1 and is mounted at /boot/efi
Checking Network interfaces...
Network interfaces:
Name: veth05e7648 (veth05e7648)
MAC Address: 46:7d:f3:35:0f:6a
MTU: 1500, Speed: 10.5 Gbps
IPv4: []
IPv6: [fe80:0:0:0:447d:f3ff:fe35:f6a]
Traffic: received 0 packets/0 bytes (0 err); transmitted 859 packets/168.1 KiB (0 err)
Name: docker0 (docker0)
MAC Address: 02:42:f0:58:02:d4
MTU: 1500, Speed: 0 bps
IPv4: [172.17.0.1]
IPv6: [fe80:0:0:0:42:f0ff:fe58:2d4]
Traffic: received 0 packets/0 bytes (0 err); transmitted 788 packets/157.7 KiB (0 err)
Name: eno1 (eno1)
MAC Address: b0:6e:bf:1f:00:ba
MTU: 1500, Speed: 1.0 Gbps
IPv4: [192.168.0.108]
IPv6: [fe80:0:0:0:85f0:3fd2:d728:3d3]
Traffic: received 1169591 packets/1.5 GiB (0 err); transmitted 612416 packets/49.7 MiB (0 err)
Checking Network parameterss...
Network parameters:
Host name: zhaohy-VC66-C
Domain name: zhaohy-VC66-C
DNS servers: [127.0.0.53]
IPv4 Gateway: 192.168.0.1
IPv6 Gateway:
Checking Displays...
Displays:
Display 0:
Manuf. ID=HN, Product ID=3541, Digital, Serial=00000001, ManufDate=3/2018, EDID v1.3
50 x 30 cm (19.7 x 11.8 in)
Preferred Timing: Clock 148MHz, Active Pixels 1920x1080
Range Limits: Field Rate 48-75 Hz vertical, 30-86 Hz horizontal, Max clock: 180 MHz
Monitor Name: HP 22f
Serial Number: 3CM8100L0L