一、包依赖
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>5.7.1</version>
</dependency>
二、测试代码
@Slf4j
public class App
{
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
try {
MqttClient client = null;
MqttConfig config = new MqttConfig();
try {
client = ClientUtils.getClient(config.getUrl(), config.getUsername(), config.getPassword());
} catch (MqttException e) {
log.error(e.getMessage());
}
if(client != null){
}
LocalDateTimeUtil.parse("2020-01-23T12:23:56");
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
OperatingSystem os = si.getOperatingSystem();
System.out.println(os);
log.info("Checking computer system...");
printComputerSystem(hal.getComputerSystem());
log.info("Checking Processor...");
printProcessor(hal.getProcessor());
log.info("Checking Memory...");
printMemory(hal.getMemory());
log.info("Checking CPU...");
printCpu(hal.getProcessor());
log.info("Checking Processes...");
printProcesses(os, hal.getMemory());
log.info("Checking Sensors...");
printSensors(hal.getSensors());
log.info("Checking Power sources...");
printPowerSources(hal.getPowerSources());
log.info("Checking Disks...");
printDisks(hal.getDiskStores());
log.info("Checking File System...");
printFileSystem(os.getFileSystem());
log.info("Checking Network interfaces...");
printNetworkInterfaces(hal.getNetworkIFs());
log.info("Checking Network parameterss...");
printNetworkParameters(os.getNetworkParams());
// hardware: displays
log.info("Checking Displays...");
printDisplays(hal.getDisplays());
// hardware: USB devices
log.info("Checking USB Devices...");
printUsbDevices(hal.getUsbDevices(true));
}catch (Exception ex){
log.error(ex.getMessage());
}
}
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" : 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());
}
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) throws InterruptedException {
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...
Thread.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() * 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:");
long[] load = processor.getSystemCpuLoadTicks();
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();
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> powerSources) {
StringBuilder sb = new StringBuilder("Power: ");
if (powerSources.size() == 0) {
sb.append("Unknown");
} else {
double timeRemaining = powerSources.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 : powerSources) {
sb.append(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacityPercent() * 100d));
}
System.out.println(sb.toString());
}
private static void printDisks(List<HWDiskStore> diskStores) {
System.out.println("Disks:");
for (HWDiskStore disk : diskStores) {
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> networkIFs) {
System.out.println("Network interfaces:");
for (NetworkIF net : networkIFs) {
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> displays) {
System.out.println("Displays:");
int i = 0;
for (Display display : displays) {
System.out.println(" Display " + i + ":");
System.out.println(display.toString());
i++;
}
}
private static void printUsbDevices(List<UsbDevice> usbDevices) {
System.out.println("USB Devices:");
for (UsbDevice usbDevice : usbDevices) {
System.out.println(usbDevice.toString());
}
}
}
三、执行结果
manufacturer: System manufacturer
model: System Product Name
serialnumber: System Serial Number
firmware:
manufacturer: American Megatrends Inc.
name: 0602
description: 0602
version: ALASKA - 1072009
release date: 2019-03-14
baseboard:
manufacturer: ASUSTeK COMPUTER INC.
model: unknown
version: Rev X.0x
serialnumber: 190347317800186
14:26:15.105 [main] INFO cn.claves.App - Checking Processor...
Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
1 physical CPU package(s)
6 physical CPU core(s)
12 logical CPU(s)
Identifier: Intel64 Family 6 Model 158 Stepping 10
ProcessorID: BFEBFBFF000906EA
Microarchitecture: Coffee Lake
1 physical CPU package(s)
6 physical CPU core(s)
12 logical CPU(s)
Identifier: Intel64 Family 6 Model 158 Stepping 10
14:26:15.152 [main] INFO cn.claves.App - Checking Memory...
Memory: 7.3 GiB/15.9 GiB
14:26:15.980 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized Paging File to Paging File
Swap used: 26.6 MiB/2.9 GiB
14:26:15.980 [main] INFO cn.claves.App - Checking CPU...
14:26:15.996 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized System to System
14:26:16.011 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized Processor to Processor
Context Switches/Interrupts: 137758754 / 86421885
14:26:16.011 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized Processor Information to Processor Information
CPU, IOWait, and IRQ ticks @ 0 sec:[2204634, 0, 1258868, 114497401, 0, 74557, 51104, 0]
CPU, IOWait, and IRQ ticks @ 1 sec:[2205244, 0, 1259259, 114508573, 0, 74572, 51104, 0]
User: 5.0% Nice: 0.0% System: 3.2% Idle: 91.7% IOwait: 0.0% IRQ: 0.1% SoftIRQ: 0.0% Steal: 0.0%
CPU load averages: N/A N/A N/A
CPU load per processor: 220524400.0% 0.0% 125925900.0% 11450857300.0% 0.0% 7457200.0% 5110400.0% 0.0%
14:26:17.074 [main] INFO cn.claves.App - Checking Processes...
Processes: 233, Threads: 3647
PID %CPU %MEM VSZ RSS Name
0 1164.0 0.0 8 KiB 8 KiB Idle
3584 0.2 0.0 199.6 MiB 2.4 MiB pcas
4 0.8 0.0 3.9 MiB 24 KiB System
14852 0.0 0.1 351.2 MiB 11.5 MiB wps
520 0.0 0.0 39.8 MiB 256 KiB smss
14:26:17.308 [main] INFO cn.claves.App - Checking Sensors...
Sensors:
14:26:17.433 [main] WARN oshi.util.platform.windows.WmiQueryHandler - COM exception querying MSAcpi_ThermalZoneTemperature, which might not be on your system. Will not attempt to query it again. Error was -2147217405: Failed to enumerate results.
CPU Temperature: 0.0°C
14:26:17.480 [main] DEBUG oshi.hardware.platform.windows.WindowsSensors - Found Fan data in WMI
Fan Speeds: [0, 0, 0]
CPU Voltage: 0.0V
14:26:17.511 [main] INFO cn.claves.App - Checking Power sources...
Power: 0:00 remaining
System Battery @ 100.0%
14:26:17.527 [main] INFO cn.claves.App - Checking Disks...
14:26:17.527 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized PhysicalDisk to PhysicalDisk
Disks:
\\.\PHYSICALDRIVE2: (model: INTEL SSDPEKNW512G8 (标准磁盘驱动器) - S/N: 0000_0000_0100_0000_E4D2_5C64_8B39_5001.) size: 512.1 GB, reads: 236464 (10.7 GiB), writes: 149604 (3.8 GiB), xfer: 224280 ms
|-- 磁盘 #2,分区 #0: GPT: Basic Data (GPT: 基本数据) Maj:Min=2:0, size: 512.1 GB @ C:\
\\.\PHYSICALDRIVE0: (model: WDC WD20EZAZ-00GGJB0 (标准磁盘驱动器) - S/N: WD-WX72A70HC3P0) size: 2.0 TB, reads: 200 (2.5 MiB), writes: 557 (3.7 MiB), xfer: 12516 ms
|-- 磁盘 #0,分区 #0: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:0, size: 542.7 GB @ E:\
|-- 磁盘 #0,分区 #1: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:1, size: 514.0 GB @ D:\
|-- 磁盘 #0,分区 #2: GPT: Basic Data (GPT: 基本数据) Maj:Min=0:2, size: 943.7 GB @ F:\
\\.\PHYSICALDRIVE1: (model: ST500LM021-1KJ152 (标准磁盘驱动器) - S/N: W62KCQVW) size: 500.1 GB, reads: 231 (356 KiB), writes: 73 (303 KiB), xfer: 640 ms
|-- 磁盘 #1,分区 #0: GPT: Basic Data (GPT: 基本数据) Maj:Min=1:0, size: 284.2 GB @ G:\
14:26:17.667 [main] INFO cn.claves.App - Checking File System...
File System:
14:26:17.667 [main] DEBUG oshi.util.platform.windows.PerfCounterQuery - Localized Process to Process
File Descriptors: 112722/16711680
本地固定磁盘 (C:) (Fixed drive) [NTFS] 358.5 GiB of 476.9 GiB free (75.2%) is \\?\Volume{41533ffd-7fe8-4f00-8491-4379800bc2e8}\ and is mounted at C:\
本地固定磁盘 (D:) (Fixed drive) [NTFS] 385.9 GiB of 478.7 GiB free (80.6%) is \\?\Volume{82ceaa01-ee9d-454a-b2d0-a1ba201390df}\ and is mounted at D:\
本地固定磁盘 (E:) (Fixed drive) [NTFS] 92.7 GiB of 505.4 GiB free (18.3%) is \\?\Volume{529369a0-0cac-45e5-97e1-582c63a971de}\ and is mounted at E:\
本地固定磁盘 (F:) (Fixed drive) [NTFS] 747.3 GiB of 878.9 GiB free (85.0%) is \\?\Volume{c0294f2a-a41c-4705-a99b-bdf25ec6c561}\ and is mounted at F:\
本地固定磁盘 (G:) (Fixed drive) [NTFS] 37.0 GiB of 264.7 GiB free (14.0%) is \\?\Volume{36d92485-b5ef-4e76-9629-ab3d23e63331}\ and is mounted at G:\
14:26:17.745 [main] INFO cn.claves.App - Checking Network interfaces...
Network interfaces:
Name: eth2 (Bluetooth Device (Personal Area Network))
MAC Address: 00:1a:7d:da:71:10
MTU: 1500, Speed: 3 Mbps
IPv4: []
IPv6: [fe80:0:0:0:e0ec:cc20:79a4:6738]
Traffic: received ?/?; transmitted ?/?
Name: eth5 (Realtek PCIe GbE Family Controller)
MAC Address: 40:b0:76:7f:4a:0d
MTU: 1500, Speed: 1 Gbps
IPv4: [192.168.99.253]
IPv6: [fe80:0:0:0:b02f:e378:3805:2b9d]
Traffic: received 106901 packets/103.5 MiB (0 err); transmitted 103493 packets/51.9 MiB (0 err)
14:26:17.995 [main] INFO cn.claves.App - Checking Network parameterss...
Network parameters:
Host name: YAPINGYANG-PC
Domain name: YapingYang-PC
DNS servers: [114.114.114.114, 223.5.5.5]
IPv4 Gateway: 192.168.99.1
IPv6 Gateway:
14:26:18.355 [main] INFO cn.claves.App - Checking Displays...
14:26:18.355 [main] DEBUG oshi.hardware.platform.windows.WindowsDisplay - Initialized WindowsDisplay
Displays:
Display 0:
14:26:18.370 [main] DEBUG oshi.util.EdidUtil - Manufacurer ID: 0011000010101110
14:26:18.370 [main] DEBUG oshi.util.EdidUtil - Serial number: [1, 1, 1, 1]
14:26:18.370 [main] DEBUG oshi.util.EdidUtil - Year-1990: 26
Manuf. ID=LEN, Product ID=60c7, Digital, Serial=01010101, ManufDate=11/2016, EDID v1.3
51 x 29 cm (20.1 x 11.4 in)
Preferred Timing: Clock 148MHz, Active Pixels 1920x1080
Serial Number: U32ZP728
Range Limits: Field Rate 50-75 Hz vertical, 30-83 Hz horizontal, Max clock: 170 MHz
Monitor Name: LEN T2324pA
14:26:18.370 [main] INFO cn.claves.App - Checking USB Devices...
USB Devices:
Intel(R) USB 3.0 可扩展主机控制器 - 1.0 (Microsoft) (通用 USB xHCI 主机控制器)
|-- USB 根集线器(USB 3.0) ((标准 USB 集线器))
|-- Generic Bluetooth Radio (Cambridge Silicon Radio Ltd.)
|-- Bluetooth Device (Personal Area Network) (Microsoft)
|-- Bluetooth Device (RFCOMM Protocol TDI) (Microsoft)
|-- Microsoft 蓝牙 LE 枚举器 (Microsoft)
|-- Microsoft 蓝牙枚举器 (Microsoft)
|-- USB Composite Device ((标准 USB 主控制器))
|-- USB 输入设备 ((标准系统设备))
|-- HID Keyboard Device ((标准键盘))
|-- USB 输入设备 ((标准系统设备))
|-- HID-compliant device ((标准系统设备))
|-- HID-compliant mouse (Microsoft)
|-- 符合 HID 标准的供应商定义设备 ((标准系统设备))
|-- 符合 HID 标准的供应商定义设备 ((标准系统设备))
|-- 符合 HID 标准的用户控制设备 (Microsoft)
|-- 符合 HID 标准的系统控制器 ((标准系统设备))
|-- 通用 USB 集线器 ((标准 USB 集线器))
|-- USB 输入设备 ((标准系统设备))
|-- HID-compliant mouse (Microsoft)
四、附件