轉(zhuǎn)載:https://www.iteye.com/blog/liningjustsoso-1254584
Sigar(System Information Gatherer And Reporter),是一個(gè)開(kāi)源的工具,提供了跨平臺(tái)的系統(tǒng)信息收集的API,由C語(yǔ)言實(shí)現(xiàn)的。
可以收集的信息包括
- CPU信息:包括基本信息(vendor、model、mhz、cacheSize)和統(tǒng)計(jì)信息(user、sys、idle、nice、wait)
- 文件系統(tǒng)信息:包括Filesystem、Size、Used、Avail、Use%、Type
- 事件信息:類似Service Control Manager
- 內(nèi)存信息:物理內(nèi)存和交換內(nèi)存的總數(shù)、使用數(shù)、剩余數(shù);RAM的大小
- 網(wǎng)絡(luò)信息:包括網(wǎng)絡(luò)接口信息和網(wǎng)絡(luò)路由信息
- 進(jìn)程信息:包括每個(gè)進(jìn)程的內(nèi)存、CPU占用數(shù)、狀態(tài)、參數(shù)、句柄
- IO信息:包括IO的狀態(tài),讀寫(xiě)大小等
- 服務(wù)狀態(tài)信息
- 系統(tǒng)信息:包括操作系統(tǒng)版本,系統(tǒng)資源限制情況,系統(tǒng)運(yùn)行時(shí)間以及負(fù)載,JAVA的版本信息等
使用Java實(shí)現(xiàn)
- 導(dǎo)入maven依賴
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
- 因?yàn)?strong>sigar是C語(yǔ)言開(kāi)發(fā)的,所以需要在系統(tǒng)中加入sigar-amd64-winnt.dll(Windows)或者libsigar-amd64-linux.so(linux)動(dòng)態(tài)庫(kù)。
- sigar-amd64-winnt.dll 加入到C:\Windows\System32中
- libsigar-amd64-linux.so 加入到/lib64目錄中
- 編寫(xiě)代碼(為了方便放在一個(gè)類里面,如有需要自行加工修改)
package cn.itsqq.controller;
import org.hyperic.sigar.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws Exception {
Main s =new Main();
System.out.println("CPU個(gè)數(shù):"+s.getCpuCount());
s.getCpuTotal();//CPU的總量(單位:HZ)及CPU的相關(guān)信息
s.testCpuPerc();//CPU的用戶使用量、系統(tǒng)使用剩余量、總的剩余量、總的使用占用量等(單位:100%)
s.getPhysicalMemory();//內(nèi)存資源信息
s.testWho();//取當(dāng)前系統(tǒng)進(jìn)程表中的用戶信息
s.testFileSystemInfo();//資源信息(主要是硬盤(pán))
s.testGetOSInfo();//取當(dāng)前操作系統(tǒng)的信息
}
/**
* 1.CPU資源信息
*/
// a)CPU數(shù)量(單位:個(gè))
public static int getCpuCount() throws SigarException {
Sigar sigar = new Sigar();
try {
return sigar.getCpuInfoList().length;
} finally {
sigar.close();
}
}
// b)CPU的總量(單位:HZ)及CPU的相關(guān)信息
public void getCpuTotal() {
Sigar sigar = new Sigar();
CpuInfo[] infos;
try {
infos = sigar.getCpuInfoList();
for (int i = 0; i < infos.length; i++) {// 不管是單塊CPU還是多CPU都適用
CpuInfo info = infos[i];
System.out.println("CPU的總量:" + info.getMhz());// CPU的總量MHz
// System.out.println("獲得CPU的廠商:" + info.getVendor());// 獲得CPU的賣主,如:Intel
// System.out.println("CPU的類別:" + info.getModel());// 獲得CPU的類別,如:Celeron
// System.out.println("緩沖存儲(chǔ)器數(shù)量:" + info.getCacheSize());// 緩沖存儲(chǔ)器數(shù)量
// System.out.println("**************");
}
} catch (SigarException e) {
e.printStackTrace();
}
}
// c)CPU的用戶使用量、系統(tǒng)使用剩余量、總的剩余量、總的使用占用量等(單位:100%)
public void testCpuPerc() {
Sigar sigar = new Sigar();
// 方式一,主要是針對(duì)一塊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();
return;
}
for (int i = 0; i < cpuList.length; i++) {
printCpuPerc(cpuList[i]);
}
}
private void printCpuPerc(CpuPerc cpu) {
System.out.println("用戶使用率:" + CpuPerc.format(cpu.getUser()));// 用戶使用率
System.out.println("系統(tǒng)使用率:" + CpuPerc.format(cpu.getSys()));// 系統(tǒng)使用率
System.out.println("當(dāng)前等待率:" + CpuPerc.format(cpu.getWait()));// 當(dāng)前等待率
System.out.println("Nice :" + CpuPerc.format(cpu.getNice()));//
System.out.println("當(dāng)前空閑率:" + CpuPerc.format(cpu.getIdle()));// 當(dāng)前空閑率
System.out.println("總的使用率:" + CpuPerc.format(cpu.getCombined()));// 總的使用率
System.out.println("**************");
}
/**
* 2.內(nèi)存資源信息
*
*/
public void getPhysicalMemory() {
// a)物理內(nèi)存信息
DecimalFormat df = new DecimalFormat("#0.00");
Sigar sigar = new Sigar();
Mem mem;
try {
mem = sigar.getMem();
// 內(nèi)存總量
System.out.println("內(nèi)存總量:" + df.format((float)mem.getTotal() / 1024/1024/1024) + "G");
// 當(dāng)前內(nèi)存使用量
System.out.println("當(dāng)前內(nèi)存使用量:" + df.format((float)mem.getUsed() / 1024/1024/1024) + "G");
// 當(dāng)前內(nèi)存剩余量
System.out.println("當(dāng)前內(nèi)存剩余量:" + df.format((float)mem.getFree() / 1024/1024/1024) + "G");
// b)系統(tǒng)頁(yè)面文件交換區(qū)信息
Swap swap = sigar.getSwap();
// 交換區(qū)總量
System.out.println("交換區(qū)總量:" + df.format((float)swap.getTotal() / 1024/1024/1024) + "G");
// 當(dāng)前交換區(qū)使用量
System.out.println("當(dāng)前交換區(qū)使用量:" + df.format((float)swap.getUsed() / 1024/1024/1024) + "G");
// 當(dāng)前交換區(qū)剩余量
System.out.println("當(dāng)前交換區(qū)剩余量:" + df.format((float)swap.getFree() / 1024/1024/1024) + "G");
} catch (SigarException e) {
e.printStackTrace();
}
}
/**
* 3.操作系統(tǒng)信息
*
*/
// a)取到當(dāng)前操作系統(tǒng)的名稱:
public String getPlatformName() {
String hostname = "";
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (Exception exc) {
Sigar sigar = new Sigar();
try {
hostname = sigar.getNetInfo().getHostName();
} catch (SigarException e) {
hostname = "localhost.unknown";
} finally {
sigar.close();
}
}
return hostname;
}
// b)取當(dāng)前操作系統(tǒng)的信息
public void testGetOSInfo() {
OperatingSystem OS = OperatingSystem.getInstance();
// 操作系統(tǒng)內(nèi)核類型如: 386、486、586等x86
System.out.println("OS.getArch() = " + OS.getArch());
System.out.println("OS.getCpuEndian() = " + OS.getCpuEndian());//
System.out.println("OS.getDataModel() = " + OS.getDataModel());//
// 系統(tǒng)描述
System.out.println("OS.getDescription() = " + OS.getDescription());
System.out.println("OS.getMachine() = " + OS.getMachine());//
// 操作系統(tǒng)類型
System.out.println("OS.getName() = " + OS.getName());
System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());//
// 操作系統(tǒng)的賣主
System.out.println("OS.getVendor() = " + OS.getVendor());
// 賣主名稱
System.out
.println("OS.getVendorCodeName() = " + OS.getVendorCodeName());
// 操作系統(tǒng)名稱
System.out.println("OS.getVendorName() = " + OS.getVendorName());
// 操作系統(tǒng)賣主類型
System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion());
// 操作系統(tǒng)的版本號(hào)
System.out.println("OS.getVersion() = " + OS.getVersion());
}
// c)取當(dāng)前系統(tǒng)進(jìn)程表中的用戶信息
public void testWho() {
try {
Sigar sigar = new Sigar();
org.hyperic.sigar.Who[] who = sigar.getWhoList();
if (who != null && who.length > 0) {
for (int i = 0; i < who.length; i++) {
System.out.println("\n~~~~~~~~~" + String.valueOf(i)
+ "~~~~~~~~~");
org.hyperic.sigar.Who _who = who[i];
System.out.println("獲取設(shè)備getDevice() = " + _who.getDevice());
System.out.println("獲得主機(jī)getHost() = " + _who.getHost());
System.out.println("獲取的時(shí)間getTime() = " + _who.getTime());
// 當(dāng)前系統(tǒng)進(jìn)程表中的用戶名
System.out.println("獲取用戶getUser() = " + _who.getUser());
}
}
} catch (SigarException e) {
e.printStackTrace();
}
}
// 4.資源信息(主要是硬盤(pán))
// a)取硬盤(pán)已有的分區(qū)及其詳細(xì)信息(通過(guò)sigar.getFileSystemList()來(lái)獲得FileSystem列表對(duì)象,然后對(duì)其進(jìn)行編歷):
public void testFileSystemInfo() throws Exception {
Sigar sigar = new Sigar();
FileSystem fslist[] = sigar.getFileSystemList();
DecimalFormat df = new DecimalFormat("#0.00");
// String dir = System.getProperty("user.home");// 當(dāng)前用戶文件夾路徑
for (int i = 0; i < fslist.length; i++) {
FileSystem fs = fslist[i];
System.out.println("\n~~~~~~~~~~" + fs.getDevName() + "~~~~~~~~~~");
// 分區(qū)的盤(pán)符名稱
System.out.println("fs.getDevName() = " + fs.getDevName());
// 分區(qū)的盤(pán)符名稱
System.out.println("fs.getDirName() = " + fs.getDirName());
System.out.println("fs.getFlags() = " + fs.getFlags());//
// 文件系統(tǒng)類型,比如 FAT32、NTFS
System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName());
// 文件系統(tǒng)類型名,比如本地硬盤(pán)、光驅(qū)、網(wǎng)絡(luò)文件系統(tǒng)等
System.out.println("fs.getTypeName() = " + fs.getTypeName());
// 文件系統(tǒng)類型
System.out.println("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 : 本地硬盤(pán)
// 文件系統(tǒng)總大小Total
System.out.println("件系統(tǒng)總大小 = " + df.format((float)usage.getTotal()/1024/1024) + "G");
// 文件系統(tǒng)剩余大小Free
System.out.println("件系統(tǒng)剩余大小 = " + df.format((float)usage.getFree()/1024/1024) + "G");
// 文件系統(tǒng)可用大小Avail
System.out.println("件系統(tǒng)可用大小 = " + df.format((float)usage.getAvail()/1024/1024) + "G");
// 文件系統(tǒng)已經(jīng)使用量Used
System.out.println("文件系統(tǒng)已經(jīng)使用量 = " + df.format((float)usage.getUsed()/1024/1024) + "G");
double usePercent = usage.getUsePercent() * 100D;
// 文件系統(tǒng)資源的利用率Usage
System.out.println("文件系統(tǒng)資源的未使用率 = " + df.format(usePercent) + "%");
// 文件系統(tǒng)資源的利用率Usage
System.out.println("文件系統(tǒng)資源的使用率 = " + (100.00-Double.parseDouble(df.format(usePercent))) + "%");
break;
case 3:// TYPE_NETWORK :網(wǎng)絡(luò)
break;
case 4:// TYPE_RAM_DISK :閃存
break;
case 5:// TYPE_CDROM :光驅(qū)
break;
case 6:// TYPE_SWAP :頁(yè)面交換
break;
}
System.out.println(" DiskReads = " + usage.getDiskReads());
System.out.println(" DiskWrites = " + usage.getDiskWrites());
}
return;
}
// 5.網(wǎng)絡(luò)信息
// a)當(dāng)前機(jī)器的正式域名
public String getFQDN() {
Sigar sigar = null;
try {
return InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
try {
sigar = new Sigar();
return sigar.getFQDN();
} catch (SigarException ex) {
return null;
} finally {
sigar.close();
}
}
}
// b)取到當(dāng)前機(jī)器的IP地址
public String getDefaultIpAddress() {
String address = null;
try {
address = InetAddress.getLocalHost().getHostAddress();
// 沒(méi)有出現(xiàn)異常而正常當(dāng)取到的IP時(shí),如果取到的不是網(wǎng)卡循回地址時(shí)就返回
// 否則再通過(guò)Sigar工具包中的方法來(lái)獲取
if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) {
return address;
}
} catch (UnknownHostException e) {
// hostname not in DNS or /etc/hosts
}
Sigar sigar = new Sigar();
try {
address = sigar.getNetInterfaceConfig().getAddress();
} catch (SigarException e) {
address = NetFlags.LOOPBACK_ADDRESS;
} finally {
sigar.close();
}
return address;
}
// c)取到當(dāng)前機(jī)器的MAC地址
public String getMAC() {
Sigar sigar = null;
try {
sigar = new Sigar();
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;
}
/*
* 如果存在多張網(wǎng)卡包括虛擬機(jī)的網(wǎng)卡,默認(rèn)只取第一張網(wǎng)卡的MAC地址,如果要返回所有的網(wǎng)卡(包括物理的和虛擬的)則可以修改方法的返回類型為數(shù)組或Collection
* ,通過(guò)在for循環(huán)里取到的多個(gè)MAC地址。
*/
hwaddr = cfg.getHwaddr();
break;
}
return hwaddr != null ? hwaddr : null;
} catch (Exception e) {
return null;
} finally {
if (sigar != null)
sigar.close();
}
}
// d)獲取網(wǎng)絡(luò)流量等信息
public void testNetIfList() throws Exception {
Sigar sigar = new Sigar();
String ifNames[] = sigar.getNetInterfaceList();
for (int i = 0; i < ifNames.length; i++) {
String name = ifNames[i];
NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
print("\nname = " + name);// 網(wǎng)絡(luò)設(shè)備名
print("Address = " + ifconfig.getAddress());// IP地址
print("Netmask = " + ifconfig.getNetmask());// 子網(wǎng)掩碼
if ((ifconfig.getFlags() & 1L) <= 0L) {
print("!IFF_UP...skipping getNetInterfaceStat");
continue;
}
try {
NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
print("RxPackets = " + ifstat.getRxPackets());// 接收的總包裹數(shù)
print("TxPackets = " + ifstat.getTxPackets());// 發(fā)送的總包裹數(shù)
print("RxBytes = " + ifstat.getRxBytes());// 接收到的總字節(jié)數(shù)
print("TxBytes = " + ifstat.getTxBytes());// 發(fā)送的總字節(jié)數(shù)
print("RxErrors = " + ifstat.getRxErrors());// 接收到的錯(cuò)誤包數(shù)
print("TxErrors = " + ifstat.getTxErrors());// 發(fā)送數(shù)據(jù)包時(shí)的錯(cuò)誤數(shù)
print("RxDropped = " + ifstat.getRxDropped());// 接收時(shí)丟棄的包數(shù)
print("TxDropped = " + ifstat.getTxDropped());// 發(fā)送時(shí)丟棄的包數(shù)
} catch (SigarNotImplementedException e) {
} catch (SigarException e) {
print(e.getMessage());
}
}
}
void print(String msg) {
System.out.println(msg);
}
// e)一些其他的信息
public void getEthernetInfo() {
Sigar sigar = null;
try {
sigar = new Sigar();
String[] ifaces = sigar.getNetInterfaceList();
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;
}
System.out.println("cfg.getAddress() = " + cfg.getAddress());// IP地址
System.out
.println("cfg.getBroadcast() = " + cfg.getBroadcast());// 網(wǎng)關(guān)廣播地址
System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());// 網(wǎng)卡MAC地址
System.out.println("cfg.getNetmask() = " + cfg.getNetmask());// 子網(wǎng)掩碼
System.out.println("cfg.getDescription() = "
+ cfg.getDescription());// 網(wǎng)卡描述信息
System.out.println("cfg.getType() = " + cfg.getType());//
System.out.println("cfg.getDestination() = "
+ cfg.getDestination());
System.out.println("cfg.getFlags() = " + cfg.getFlags());//
System.out.println("cfg.getMetric() = " + cfg.getMetric());
System.out.println("cfg.getMtu() = " + cfg.getMtu());
System.out.println("cfg.getName() = " + cfg.getName());
System.out.println();
}
} catch (Exception e) {
System.out.println("Error while creating GUID" + e);
} finally {
if (sigar != null)
sigar.close();
}
}
}
- 項(xiàng)目案例(這個(gè)是項(xiàng)目實(shí)現(xiàn)案例,不是上面代碼實(shí)現(xiàn),上面代碼只是工具代碼)

sigar實(shí)現(xiàn)服務(wù)器系統(tǒng)信息收集