歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中獲取系統相關信息——sigar

Java中獲取系統相關信息——sigar

日期:2017/3/1 9:33:52   编辑:Linux編程

一、sigar簡介

sigar中文名是系統信息收集和報表工具,是一個開源的工具,提供了跨平台的系統信息收集的API,可以和絕大多數操作系統和大多數版本打交道,可以收集的信息包括:
1.操作系統的信息,包括:dataModel、cpuEndian、name、version、arch、machine、description、patchLevel、vendor、vendorVersion、vendorName、vendorCodeName
2.CPU信息,包括:基本信息(vendor、model、mhz、cacheSize)和統計信息(user、sys、idle、nice、wait)
3.內存信息,物理內存和交換內存的總數、使用數、剩余數;RAM的大小
4.進程信息,包括每個進程的內存、CPU占用數、狀態、參數、句柄等。
5.文件系統信息,包括名稱、容量、剩余數、使用數、分區類型等
6.網絡接口信息,包括基本信息和統計信息。
7.網絡路由和鏈接表信息。

二、sigar的使用

//接口定義

public interface LoadInfo {
//獲取cpu使用率
public String getCpuInfo();
// 獲取系統內存使用量
public String getRamInfo();
//獲取網絡使用流量
public String getNetworkInfo();
//獲取操作系統信息
public String getSystemInfo();
// 獲取運行環境信息
public String getRunLoadInfo();
//獲取虛擬機剩余內存
public String getVmRamInfo();
}

//以下是接口的實現

獲取cpu信息代碼
// CPU數量(單位:個)
int cpuLength = sigar.getCpuInfoList().length;
print(cpuLength);

// CPU的總量(單位:HZ)及CPU的相關信息
CpuInfo infos[] = sigar.getCpuInfoList();
for (int i = 0; i < infos.length; i++) {// 不管是單塊CPU還是多CPU都適用
CpuInfo info = infos[i];
print("mhz=" + info.getMhz());// CPU的總量MHz
print("vendor=" + info.getVendor());// 獲得CPU的賣主,如:Intel
print("model=" + info.getModel());// 獲得CPU的類別,如:Celeron
print("cache size=" + info.getCacheSize());// 緩沖存儲器數量
}


// 方式一,主要是針對一塊CPU的情況
CpuPerc cpu;
try {
cpu = sigar.getCpuPerc();
printCpuPerc(cpu);
} catch (SigarException e) {
e.printStackTrace();
}

// 方式二,不管是單塊CPU還是多CPU都適用
CpuPerc cpuList[] = null;
try {
cpuList = sigar.getCpuPercList();
} catch (SigarException e) {
e.printStackTrace();
}
for (int i = 0; i < cpuList.length; i++) {
// printCpuPerc(cpuList[i]);
}

獲取內存信息代碼
// 物理內存信息
Mem mem = sigar.getMem();
// 內存總量
print("Total = " + mem.getTotal() / 1024L / 1024 + "M av");
// 當前內存使用量
print("Used = " + mem.getUsed() / 1024L / 1024 + "M used");
// 當前內存剩余量
print("Free = " + mem.getFree() / 1024L / 1024 + "M free");

// 系統頁面文件交換區信息
Swap swap = sigar.getSwap();
// 交換區總量
print("Total = " + swap.getTotal() / 1024L + "K av");
// 當前交換區使用量
print("Used = " + swap.getUsed() / 1024L + "K used");
// 當前交換區剩余量
print("Free = " + swap.getFree() / 1024L + "K free");

獲取操作系統信息代碼

// 取到當前操作系統的名稱
String hostname = "";
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (Exception exc) {
try {
hostname = sigar.getNetInfo().getHostName();
} catch (SigarException e) {
hostname = "localhost.unknown";
} finally {
sigar.close();
}
}
print(hostname);

// 取當前操作系統的信息
OperatingSystem OS = OperatingSystem.getInstance();
// 操作系統內核類型如: 386、486、586等x86
print("OS.getArch() = " + OS.getArch());
print("OS.getCpuEndian() = " + OS.getCpuEndian());//
print("OS.getDataModel() = " + OS.getDataModel());//
// 系統描述
print("OS.getDescription() = " + OS.getDescription());
print("OS.getMachine() = " + OS.getMachine());//
// 操作系統類型
print("OS.getName() = " + OS.getName());
print("OS.getPatchLevel() = " + OS.getPatchLevel());//
// 操作系統的賣主
print("OS.getVendor() = " + OS.getVendor());
// 賣主名稱
System.out
.println("OS.getVendorCodeName() = " + OS.getVendorCodeName());
// 操作系統名稱
print("OS.getVendorName() = " + OS.getVendorName());
// 操作系統賣主類型
print("OS.getVendorVersion() = " + OS.getVendorVersion());
// 操作系統的版本號
print("OS.getVersion() = " + OS.getVersion());

// 取當前系統進程表中的用戶信息
Who who[] = sigar.getWhoList();
if (who != null && who.length > 0) {
for (int i = 0; i < who.length; i++) {
print("\n~~~~~~~~~" + String.valueOf(i) + "~~~~~~~~~");
Who _who = who[i];
print("getDevice() = " + _who.getDevice());
print("getHost() = " + _who.getHost());
print("getTime() = " + _who.getTime());
// 當前系統進程表中的用戶名
print("getUser() = " + _who.getUser());
}
}

獲取磁盤信息代碼
// 取硬盤已有的分區及其詳細信息(通過sigar.getFileSystemList()來獲得FileSystem列表對象,然後對其進行編歷
FileSystem fslist[] = sigar.getFileSystemList();
String dir = System.getProperty("user.home");// 當前用戶文件夾路徑
print(dir + " " + fslist.length);
for (int i = 0; i < fslist.length; i++) {
print("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
FileSystem fs = fslist[i];
// 分區的盤符名稱
print("fs.getDevName() = " + fs.getDevName());
// 分區的盤符名稱
print("fs.getDirName() = " + fs.getDirName());
print("fs.getFlags() = " + fs.getFlags());//
// 文件系統類型,比如 FAT32、NTFS
print("fs.getSysTypeName() = " + fs.getSysTypeName());
// 文件系統類型名,比如本地硬盤、光驅、網絡文件系統等
print("fs.getTypeName() = " + fs.getTypeName());
// 文件系統類型
print("fs.getType() = " + fs.getType());
FileSystemUsage usage = null;
try {
usage = sigar.getFileSystemUsage(fs.getDirName());
} catch (SigarException e) {
if (fs.getType() == 2)
throw e;
continue;
}
switch (fs.getType()) {
case 0: // TYPE_UNKNOWN :未知
break;
case 1: // TYPE_NONE
break;
case 2: // TYPE_LOCAL_DISK : 本地硬盤
// 文件系統總大小
print(" Total = " + usage.getTotal() + "KB");
// 文件系統剩余大小
print(" Free = " + usage.getFree() + "KB");
// 文件系統可用大小
print(" Avail = " + usage.getAvail() + "KB");
// 文件系統已經使用量
print(" Used = " + usage.getUsed() + "KB");
double usePercent = usage.getUsePercent() * 100D;
// 文件系統資源的利用率
print(" Usage = " + usePercent + "%");
break;
case 3:// TYPE_NETWORK :網絡
break;
case 4:// TYPE_RAM_DISK :閃存
break;
case 5:// TYPE_CDROM :光驅
break;
case 6:// TYPE_SWAP :頁面交換
break;
}
print(" DiskReads = " + usage.getDiskReads());
print(" DiskWrites = " + usage.getDiskWrites());
}

獲取網絡信息代碼
// 當前機器的正式域名
try {
print(InetAddress.getLocalHost().getCanonicalHostName());
} catch (UnknownHostException e) {
try {
print(sigar.getFQDN());
} catch (SigarException ex) {
} finally {
sigar.close();
}
}

// 取到當前機器的IP地址
String address = null;
try {
address = InetAddress.getLocalHost().getHostAddress();
// 沒有出現異常而正常當取到的IP時,如果取到的不是網卡循回地址時就返回
// 否則再通過Sigar工具包中的方法來獲取
print(address);
if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) {
}
} catch (UnknownHostException e) {
// hostname not in DNS or /etc/hosts
}
try {
address = sigar.getNetInterfaceConfig().getAddress();
} catch (SigarException e) {
address = NetFlags.LOOPBACK_ADDRESS;
} finally {
}
print(address);

// 取到當前機器的MAC地址
String[] ifaces = sigar.getNetInterfaceList();
String hwaddr = null;
for (int i = 0; i < ifaces.length; i++) {
NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
|| (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
continue;
}
hwaddr = cfg.getHwaddr();
print(hwaddr);
// break;
}
print(hwaddr != null ? hwaddr : null);

// 獲取網絡流量等信息
String ifNames[] = sigar.getNetInterfaceList();
for (int i = 0; i < ifNames.length; i++) {
String name = ifNames[i];
NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
print("\nname = " + name);// 網絡設備名
print("Address = " + ifconfig.getAddress());// IP地址
print("Netmask = " + ifconfig.getNetmask());// 子網掩碼
if ((ifconfig.getFlags() & 1L) <= 0L) {
print("!IFF_UP...skipping getNetInterfaceStat");
continue;
}
try {
NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
print("RxPackets = " + ifstat.getRxPackets());// 接收的總包裹數
print("TxPackets = " + ifstat.getTxPackets());// 發送的總包裹數
print("RxBytes = " + ifstat.getRxBytes());// 接收到的總字節數
print("TxBytes = " + ifstat.getTxBytes());// 發送的總字節數
print("RxErrors = " + ifstat.getRxErrors());// 接收到的錯誤包數
print("TxErrors = " + ifstat.getTxErrors());// 發送數據包時的錯誤數
print("RxDropped = " + ifstat.getRxDropped());// 接收時丟棄的包數
print("TxDropped = " + ifstat.getTxDropped());// 發送時丟棄的包數
} catch (SigarNotImplementedException e) {
} catch (SigarException e) {
print(e.getMessage());
}
}

// 一些其他的信息
for (int i = 0; i < ifaces.length; i++) {
NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
|| (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
continue;
}
print("cfg.getAddress() = " + cfg.getAddress());// IP地址
print("cfg.getBroadcast() = " + cfg.getBroadcast());// 網關廣播地址
print("cfg.getHwaddr() = " + cfg.getHwaddr());// 網卡MAC地址
print("cfg.getNetmask() = " + cfg.getNetmask());// 子網掩碼
System.out
.println("cfg.getDescription() = " + cfg.getDescription());// 網卡描述信息
print("cfg.getType() = " + cfg.getType());//
System.out
.println("cfg.getDestination() = " + cfg.getDestination());
print("cfg.getFlags() = " + cfg.getFlags());//
print("cfg.getMetric() = " + cfg.getMetric());
print("cfg.getMtu() = " + cfg.getMtu());
print("cfg.getName() = " + cfg.getName());
}

三、sigar的包及相關文件

該類需要引入jar包,另外為了防止程序運行時的錯誤,還需要相關文件,進入下載

--------------------------------------分割線 --------------------------------------

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2015年資料/2月/3日/Java中獲取系統相關信息——sigar/

下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm

--------------------------------------分割線 --------------------------------------

四、在Windows中的常見問題

使用該類常常會遇到問題:

java.lang.UnsatisfiedLinkError: org.hyperic.sigar.SysInfo.gather(Lorg/hyperic/sigar/Sigar;)V
org.hyperic.sigar.SysInfo.gather(Native Method)
org.hyperic.sigar.OperatingSystem.getInstance(OperatingSystem.java:90)
com.shuhaiserver.page.servlet.LoginServlet.doLogin(LoginServlet.java:146)
com.shuhaiserver.page.servlet.LoginServlet.doPost(LoginServlet.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
com.shuhaiserver.page.servlet.MyFilter.doFilter(MyFilter.java:82)

此時,需要將libsigar-amd64-linux.so、libsigar-x86-linux.so、sigar-amd64-winnt.dll、sigar-x86-winnt.dll、sigar-x86-winnt.lib文件放在項目的lib文件夾下

五、在Linux中的常見問題

如果在Linux中還會包如上問題,可以嘗試將相關文件放在項目的src文件夾下

Copyright © Linux教程網 All Rights Reserved