oshi-core sigar 获取服务器系统信息的工具, snmp协议
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.5.0</version>
</dependency>
OshiTest.java
package com.imddy.demo.test;
import java.text.DecimalFormat;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
public class OshiTest {
public static void main(String[] args) {
while (true){
try {
OshiTest.printlnCpuInfo();
OshiTest.MemInfo();
OshiTest.getThread();
OshiTest.setSysInfo();
OshiTest.setJvmInfo();
TimeUnit.SECONDS.sleep(5);
}catch (Exception e){
e.printStackTrace();
}
}
}
private static void printlnCpuInfo() throws InterruptedException {
//System.out.println("----------------cpu信息----------------");
SystemInfo systemInfo = new SystemInfo();
CentralProcessor processor = systemInfo.getHardware().getProcessor();
long[] prevTicks = processor.getSystemCpuLoadTicks();
// 睡眠1s
TimeUnit.SECONDS.sleep(1);
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;
System.out.println("----------------cpu信息----------------");
System.out.println("cpu核数:" + processor.getLogicalProcessorCount());
System.out.println("cpu系统使用率:" + new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
System.out.println("cpu用户使用率:" + new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
System.out.println("cpu当前等待率:" + new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
System.out.println("cpu当前使用率:" + new DecimalFormat("#.##%").format(1.0-(idle * 1.0 / totalCpu)));
}
public static void MemInfo(){
System.out.println("----------------主机内存信息----------------");
SystemInfo systemInfo = new SystemInfo();
GlobalMemory memory = systemInfo.getHardware().getMemory();
//总内存
long totalByte = memory.getTotal();
//剩余
long acaliableByte = memory.getAvailable();
System.out.println("总内存 = " + formatByte(totalByte));
System.out.println("使用" + formatByte(totalByte-acaliableByte));
System.out.println("剩余内存 = " + formatByte(acaliableByte));
System.out.println("使用率:" + new DecimalFormat("#.##%").format((totalByte-acaliableByte)*1.0/totalByte));
}
public static void setSysInfo(){
System.out.println("----------------操作系统信息----------------");
Properties props = System.getProperties();
//系统名称
String osName = props.getProperty("os.name");
//架构名称
String osArch = props.getProperty("os.arch");
System.out.println("操作系统名 = " + osName);
System.out.println("系统架构 = " + osArch);
}
public static void setJvmInfo(){
System.out.println("----------------jvm信息----------------");
Properties props = System.getProperties();
Runtime runtime = Runtime.getRuntime();
//jvm总内存
long jvmTotalMemoryByte = runtime.totalMemory();
//jvm最大可申请
long jvmMaxMoryByte = runtime.maxMemory();
//空闲空间
long freeMemoryByte = runtime.freeMemory();
//jdk版本
String jdkVersion = props.getProperty("java.version");
//jdk路径
String jdkHome = props.getProperty("java.home");
System.out.println("jvm内存总量 = " + formatByte(jvmTotalMemoryByte));
System.out.println("jvm已使用内存 = " + formatByte(jvmTotalMemoryByte-freeMemoryByte));
System.out.println("jvm剩余内存 = " + formatByte(freeMemoryByte));
System.out.println("jvm内存使用率 = " + new DecimalFormat("#.##%").format((jvmTotalMemoryByte-freeMemoryByte)*1.0/jvmTotalMemoryByte));
System.out.println("java版本 = " + jdkVersion);
//System.out.println("jdkHome = " + jdkHome);
}
public static void getThread(){
System.out.println("----------------线程信息----------------");
ThreadGroup currentGroup =Thread.currentThread().getThreadGroup();
while (currentGroup.getParent()!=null){
// 返回此线程组的父线程组
currentGroup=currentGroup.getParent();
}
//此线程组中活动线程的估计数
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
//把对此线程组中的所有活动子组的引用复制到指定数组中。
currentGroup.enumerate(lstThreads);
for (Thread thread : lstThreads) {
System.out.println("线程数量:"+noThreads+" 线程id:" + thread.getId() + " 线程名称:" + thread.getName() + " 线程状态:" + thread.getState());
}
}
public 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);
}
}
SystemInfoTest.java
package com.imddy.demo.test;
import static org.junit.Assert.assertFalse;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.PlatformEnum;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.ComputerSystem;
import oshi.hardware.Display;
import oshi.hardware.GlobalMemory;
import oshi.hardware.GraphicsCard;
import oshi.hardware.HWDiskStore;
import oshi.hardware.HWPartition;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;
import oshi.hardware.PhysicalMemory;
import oshi.hardware.PowerSource;
import oshi.hardware.Sensors;
import oshi.hardware.SoundCard;
import oshi.hardware.UsbDevice;
import oshi.hardware.VirtualMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.InternetProtocolStats;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSFileStore;
import oshi.software.os.OSProcess;
import oshi.software.os.OSService;
import oshi.software.os.OperatingSystem;
import oshi.software.os.OperatingSystem.ProcessSort;
import oshi.util.FormatUtil;
import oshi.util.Util;
/**
* A demonstration of access to many of OSHI's capabilities
*/
public class SystemInfoTest {
private static final Logger logger = LoggerFactory.getLogger(SystemInfoTest.class);
static List<String> oshi = new ArrayList<>();
/**
* Test that this platform is implemented..
*/
@Test
public void testPlatformEnum() {
assertFalse(PlatformEnum.UNKNOWN.equals(SystemInfo.getCurrentPlatformEnum()));
// Exercise the main method
main(null);
}
/**
* The main method, demonstrating use of classes.
*
* @param args
* the arguments (unused)
*/
public static void main(String[] args) {
logger.info("Initializing System...");
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
OperatingSystem os = si.getOperatingSystem();
printOperatingSystem(os);
logger.info("Checking computer system...");
printComputerSystem(hal.getComputerSystem());
logger.info("Checking Processor...");
printProcessor(hal.getProcessor());
logger.info("Checking Memory...");
printMemory(hal.getMemory());
logger.info("Checking CPU...");
printCpu(hal.getProcessor());
logger.info("Checking Processes...");
printProcesses(os, hal.getMemory());
logger.info("Checking Services...");
printServices(os);
logger.info("Checking Sensors...");
printSensors(hal.getSensors());
logger.info("Checking Power sources...");
printPowerSources(Arrays.asList( hal.getPowerSources() ));
logger.info("Checking Disks...");
printDisks(Arrays.asList( hal.getDiskStores() ));
logger.info("Checking File System...");
printFileSystem(os.getFileSystem());
logger.info("Checking Network interfaces...");
printNetworkInterfaces(Arrays.asList( hal.getNetworkIFs()));
logger.info("Checking Network parameters...");
printNetworkParameters(os.getNetworkParams());
logger.info("Checking IP statistics...");
printInternetProtocolStats(os.getInternetProtocolStats());
// hardware: displays
logger.info("Checking Displays...");
printDisplays(Arrays.asList( hal.getDisplays()));
// hardware: USB devices
logger.info("Checking USB Devices...");
printUsbDevices(Arrays.asList( hal.getUsbDevices(true) ));
logger.info("Checking Sound Cards...");
printSoundCards(Arrays.asList( hal.getSoundCards() ));
logger.info("Checking Graphics Cards...");
printGraphicsCards(Arrays.asList( hal.getGraphicsCards()));
StringBuilder output = new StringBuilder();
for (int i = 0; i < oshi.size(); i++) {
output.append(oshi.get(i));
if (oshi.get(i) != null && !oshi.get(i).endsWith("\n")) {
output.append('\n');
}
}
logger.info("Printing Operating System and Hardware Info:{}{}", '\n', output);
}
private static void printOperatingSystem(final OperatingSystem os) {
oshi.add(String.valueOf(os));
oshi.add("Booted: " + Instant.ofEpochSecond(os.getSystemBootTime()));
oshi.add("Uptime: " + FormatUtil.formatElapsedSecs(os.getSystemUptime()));
oshi.add("Running with" + (os.isElevated() ? "" : "out") + " elevated permissions.");
}
private static void printComputerSystem(final ComputerSystem computerSystem) {
oshi.add("system: " + computerSystem.toString());
oshi.add(" firmware: " + computerSystem.getFirmware().toString());
oshi.add(" baseboard: " + computerSystem.getBaseboard().toString());
}
private static void printProcessor(CentralProcessor processor) {
oshi.add(processor.toString());
}
private static void printMemory(GlobalMemory memory) {
oshi.add("Physical Memory: \n " + memory.toString());
VirtualMemory vm = memory.getVirtualMemory();
oshi.add("Virtual Memory: \n " + vm.toString());
PhysicalMemory[] pmArray = memory.getPhysicalMemory();
if (pmArray.length > 0) {
oshi.add("Physical Memory: ");
for (PhysicalMemory pm : pmArray) {
oshi.add(" " + pm.toString());
}
}
}
private static void printCpu(CentralProcessor processor) {
oshi.add("Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());
long[] prevTicks = processor.getSystemCpuLoadTicks();
long[][] prevProcTicks = processor.getProcessorCpuLoadTicks();
oshi.add("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));
// Wait a second...
Util.sleep(1000);
long[] ticks = processor.getSystemCpuLoadTicks();
oshi.add("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;
oshi.add(String.format(
"User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%",
100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu));
oshi.add(String.format("CPU load: %.1f%%", processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100));
double[] loadAverage = processor.getSystemLoadAverage(3);
oshi.add("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(prevProcTicks);
for (double avg : load) {
procCpu.append(String.format(" %.1f%%", avg * 100));
}
oshi.add(procCpu.toString());
long freq = processor.getProcessorIdentifier().getVendorFreq();
if (freq > 0) {
oshi.add("Vendor Frequency: " + FormatUtil.formatHertz(freq));
}
freq = processor.getMaxFreq();
if (freq > 0) {
oshi.add("Max Frequency: " + FormatUtil.formatHertz(freq));
}
long[] freqs = processor.getCurrentFreq();
if (freqs[0] > 0) {
StringBuilder sb = new StringBuilder("Current Frequencies: ");
for (int i = 0; i < freqs.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(FormatUtil.formatHertz(freqs[i]));
}
oshi.add(sb.toString());
}
}
private static void printProcesses(OperatingSystem os, GlobalMemory memory) {
oshi.add("My PID: " + os.getProcessId() + " with affinity "
+ Long.toBinaryString(os.getProcessAffinityMask(os.getProcessId())));
oshi.add("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
// Sort by highest CPU
List<OSProcess> procs = Arrays.asList(os.getProcesses(5, ProcessSort.CPU));
oshi.add(" PID %CPU %MEM VSZ RSS Name");
for (int i = 0; i < procs.size() && i < 5; i++) {
OSProcess p = procs.get(i);
oshi.add(String.format(" %5d %5.1f %4.1f %9s %9s %s", 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 printServices(OperatingSystem os) {
oshi.add("Services: ");
oshi.add(" PID State Name");
// DO 5 each of running and stopped
int i = 0;
for (OSService s : os.getServices()) {
if (s.getState().equals(OSService.State.RUNNING) && i++ < 5) {
oshi.add(String.format(" %5d %7s %s", s.getProcessID(), s.getState(), s.getName()));
}
}
i = 0;
for (OSService s : os.getServices()) {
if (s.getState().equals(OSService.State.STOPPED) && i++ < 5) {
oshi.add(String.format(" %5d %7s %s", s.getProcessID(), s.getState(), s.getName()));
}
}
}
private static void printSensors(Sensors sensors) {
oshi.add("Sensors: " + sensors.toString());
}
private static void printPowerSources(List<PowerSource> list) {
StringBuilder sb = new StringBuilder("Power Sources: ");
if (list.isEmpty()) {
sb.append("Unknown");
}
for (PowerSource powerSource : list) {
sb.append("\n ").append(powerSource.toString());
}
oshi.add(sb.toString());
}
private static void printDisks(List<HWDiskStore> list) {
oshi.add("Disks:");
for (HWDiskStore disk : list) {
oshi.add(" " + disk.toString());
List<HWPartition> partitions = Arrays.asList( disk.getPartitions());
for (HWPartition part : partitions) {
oshi.add(" |-- " + part.toString());
}
}
}
private static void printFileSystem(FileSystem fileSystem) {
oshi.add("File System:");
oshi.add(String.format(" File Descriptors: %d/%d", fileSystem.getOpenFileDescriptors(),
fileSystem.getMaxFileDescriptors()));
OSFileStore[] fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long usable = fs.getUsableSpace();
long total = fs.getTotalSpace();
oshi.add(String.format(
" %s (%s) [%s] %s of %s free (%.1f%%), %s of %s files free (%.1f%%) is %s "
+ (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")
+ " and is mounted at %s",
fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
FormatUtil.formatValue(fs.getFreeInodes(), ""), FormatUtil.formatValue(fs.getTotalInodes(), ""),
100d * fs.getFreeInodes() / fs.getTotalInodes(), fs.getVolume(), fs.getLogicalVolume(),
fs.getMount()));
}
}
private static void printNetworkInterfaces(List<NetworkIF> list) {
StringBuilder sb = new StringBuilder("Network Interfaces:");
if (list.isEmpty()) {
sb.append(" Unknown");
} else {
for (NetworkIF net : list) {
sb.append("\n ").append(net.toString());
}
}
oshi.add(sb.toString());
}
private static void printNetworkParameters(NetworkParams networkParams) {
oshi.add("Network parameters:\n " + networkParams.toString());
}
private static void printInternetProtocolStats(InternetProtocolStats ip) {
oshi.add("Internet Protocol statistics:");
oshi.add(" TCPv4: " + ip.getTCPv4Stats());
oshi.add(" TCPv6: " + ip.getTCPv6Stats());
oshi.add(" UDPv4: " + ip.getUDPv4Stats());
oshi.add(" UDPv6: " + ip.getUDPv6Stats());
}
private static void printDisplays(List<Display> list) {
oshi.add("Displays:");
int i = 0;
for (Display display : list) {
oshi.add(" Display " + i + ":");
oshi.add(String.valueOf(display));
i++;
}
}
private static void printUsbDevices(List<UsbDevice> list) {
oshi.add("USB Devices:");
for (UsbDevice usbDevice : list) {
oshi.add(String.valueOf(usbDevice));
}
}
private static void printSoundCards(List<SoundCard> list) {
oshi.add("Sound Cards:");
for (SoundCard card : list) {
oshi.add(" " + String.valueOf(card));
}
}
private static void printGraphicsCards(List<GraphicsCard> list) {
oshi.add("Graphics Cards:");
if (list.isEmpty()) {
oshi.add(" None detected.");
} else {
for (GraphicsCard card : list) {
oshi.add(" " + String.valueOf(card));
}
}
}
}