通過Hyperic-hq産品的基礎包sigar.jar來實作伺服器狀态資料的擷取。Sigar.jar包是通過本地方法來調用作業系統API來擷取系統相關資料。Windows作業系統下Sigar.jar依賴sigar-amd64-winnt.dll或sigar-x86-winnt.dll,linux 作業系統下則依賴libsigar-amd64-linux.so或libsigar-x86-linux.so……而Sigar.jar還依賴于jug-asl-2.0.0.jar、log4j-1.2.14.jar、Junit.jar,
Sigar.jar包的使用方法:
1、 CPU資源資訊
a) CPU數量(機關:個)
privatestaticint getCpuCount() throws SigarException {
Sigar sigar = new Sigar();
try {
return sigar.getCpuInfoList().length;
} finally {
sigar.close();
}
}
b) CPU的總量(機關:HZ)及CPU的相關資訊
Sigar sigar = getSigar();
CpuInfo infos[] = sigar.getCpuInfoList();
for (int i = 0; i < infos.length; i++) {//不管是單塊CPU還是多CPU都适用
CpuInfo info = infos[i];
traceln("mhz=" + info.getMhz());//CPU的總量MHz
traceln("vendor=" + info.getVendor());//獲得CPU的賣主,如:Intel
traceln("model=" + info.getModel());//獲得CPU的類别,如:Celeron
traceln("cache size=" + info.getCacheSize());//緩沖存儲器數量
c) CPU的使用者使用量、系統使用剩餘量、總的剩餘量、總的使用占用量等(機關:100%)
publicvoid testCpuPerc() {
Sigar sigar = new Sigar();
// 方式一,主要是針對一塊CPU的情況
CpuPerc cpu;
try {
cpu = sigar.getCpuPerc();
printCpuPerc(cpu);
} catch (SigarException e) {
e.printStackTrace();
}
// 方式二,不管是單塊CPU還是多CPU都适用
CpuPerc cpuList[] = null;
cpuList = sigar.getCpuPercList();
return;
for (int i = 0; i < cpuList.length; i++) {
printCpuPerc(cpuList[i]);
}
privatevoid printCpuPerc(CpuPerc cpu) {
println("User :" + CpuPerc.format(cpu.getUser()));// 使用者使用率
println("Sys :" + CpuPerc.format(cpu.getSys()));// 系統使用率
println("Wait :" + CpuPerc.format(cpu.getWait()));// 目前等待率
println("Nice :" + CpuPerc.format(cpu.getNice()));//
println("Idle :" + CpuPerc.format(cpu.getIdle()));// 目前空閑率
println("Total :" + CpuPerc.format(cpu.getCombined()));// 總的使用率
d) ……
2、 記憶體資源資訊
a) 實體記憶體資訊
Sigar sigar = new Sigar();
Mem mem = sigar.getMem();
// 記憶體總量
System.out.println("Total = " + mem.getTotal() / 1024L + "K av");
// 目前記憶體使用量
System.out.println("Used = " + mem.getUsed() / 1024L + "K used");
// 目前記憶體剩餘量
System.out.println("Free = " + mem.getFree() / 1024L + "K free");
b) 系統頁面檔案交換區資訊
Swap swap = sigar.getSwap();
// 交換區總量
System.out.println("Total = " + swap.getTotal() / 1024L + "K av");
// 目前交換區使用量
System.out.println("Used = " + swap.getUsed() / 1024L + "K used");
// 目前交換區剩餘量
System.out.println("Free = " + swap.getFree() / 1024L + "K free");
c) ……
3、 作業系統資訊
a) 取到目前作業系統的名稱:
private String getPlatformName() {
String hostname = "";
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) 取目前作業系統的資訊
publicvoid testGetOSInfo() {
OperatingSystem OS = OperatingSystem.getInstance();
// 作業系統核心類型如: 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());//
// 系統描述
System.out.println("OS.getDescription() = " + OS.getDescription());
System.out.println("OS.getMachine() = " + OS.getMachine());//
// 作業系統類型
System.out.println("OS.getName() = " + OS.getName());
System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());//
// 作業系統的賣主
System.out.println("OS.getVendor() = " + OS.getVendor());
// 賣主名稱
System.out.println("OS.getVendorCodeName() = " + OS.getVendorCodeName());
// 作業系統名稱
System.out.println("OS.getVendorName() = " + OS.getVendorName());
// 作業系統賣主類型
System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion());
// 作業系統的版本号
System.out.println("OS.getVersion() = " + OS.getVersion());
c) 取目前系統程序表中的使用者資訊
publicvoid testWho() {
Sigar sigar = new Sigar();
Who who[] = sigar.getWhoList();
if (who != null && who.length > 0) {
for (int i = 0; i < who.length; i++) {
Sysout.out.println("/n~~~~~~~~~" + String.valueOf(i) + "~~~~~~~~~");
Who _who = who[i];
Sysout.out.println ("getDevice() = " + _who.getDevice());
Sysout.out.println ("getHost() = " + _who.getHost());
Sysout.out.println ("getTime() = " + _who.getTime());
//目前系統程序表中的使用者名
Sysout.out.println ("getUser() = " + _who.getUser());
}
4、 資源資訊(主要是硬碟)
a) 取硬碟已有的分區及其詳細資訊(通過sigar.getFileSystemList()來獲得FileSystem清單對象,然後對其進行編曆):
publicvoid testFileSystemInfo() throws Exception {
Sigar sigar = getSigar();
FileSystem fslist[] = sigar.getFileSystemList();
String dir = System.getProperty("user.home");//目前使用者檔案夾路徑
for (int i = 0; i < fslist.length; i++) {
System.out.println("/n~~~~~~~~~~" + i + "~~~~~~~~~~");
FileSystem fs = fslist[i];
// 分區的盤符名稱
System.out.println("fs.getDevName() = " + fs.getDevName());
System.out.println("fs.getDirName() = " + fs.getDirName());
System.out.println("fs.getFlags() = " + fs.getFlags());//
// 檔案系統類型,比如 FAT32、NTFS
System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName());
// 檔案系統類型名,比如本地硬碟、光驅、網絡檔案系統等
System.out.println("fs.getTypeName() = " + fs.getTypeName());
// 檔案系統類型
System.out.println("fs.getType() = " + fs.getType());
FileSystemUsage usage = null;
usage = sigar.getFileSystemUsage(fs.getDirName());
if (fs.getType() == 2)
throw e;
continue;
switch (fs.getType()) {
case 0: // TYPE_UNKNOWN :未知
break;
case 1: // TYPE_NONE
case 2: // TYPE_LOCAL_DISK : 本地硬碟
// 檔案系統總大小
System.out.println(" Total = " + usage.getTotal() + "KB");
// 檔案系統剩餘大小
System.out.println(" Free = " + usage.getFree() + "KB");
// 檔案系統可用大小
System.out.println(" Avail = " + usage.getAvail() + "KB");
// 檔案系統已經使用量
System.out.println(" Used = " + usage.getUsed() + "KB");
double usePercent = usage.getUsePercent() * 100D;
// 檔案系統資源的使用率
System.out.println(" Usage = " + usePercent + "%");
break;
case 3:// TYPE_NETWORK :網絡
case 4:// TYPE_RAM_DISK :閃存
case 5:// TYPE_CDROM :光驅
case 6:// TYPE_SWAP :頁面交換
System.out.println(" DiskReads = " + usage.getDiskReads());
System.out.println(" DiskWrites = " + usage.getDiskWrites());
return;
b) ……
5、 網絡資訊
a) 目前機器的正式域名
public String getFQDN(){
return InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
Sigar sigar = new Sigar();
return sigar.getFQDN();
} catch (SigarException ex) {
returnnull;
sigar.close();
}
b) 取到目前機器的IP位址
public String getDefaultIpAddress() {
String address = null;
try {
address = InetAddress.getLocalHost().getHostAddress();
// 沒有出現異常而正常當取到的IP時,如果取到的不是網卡循回位址時就傳回
// 否則再通過Sigar工具包中的方法來擷取
if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) {
return address;
}
} catch (UnknownHostException e) {
//hostname not in DNS or /etc/hosts
}
Sigar sigar = new Sigar();
address = sigar.getNetInterfaceConfig().getAddress();
} catch (SigarException e) {
address = NetFlags.LOOPBACK_ADDRESS;
} finally {
sigar.close();
return address;
c) 取到目前機器的MAC位址
public String getMAC() {
Sigar sigar = null;
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;
/*如果存在多張網卡包括虛拟機的網卡,預設隻取第一張網卡的MAC位址,如果要傳回所有的網卡(包括實體的和虛拟的)則可以修改方法的傳回類型為數組或Collection,通過在for循環裡取到的多個MAC位址。*/
hwaddr = cfg.getHwaddr();
return hwaddr != null ? hwaddr : null;
} catch (Exception e) {
returnnull;
} finally {
if (sigar != null)
sigar.close();
d) 根據MAC位址來獲得一個GUID号
public String getGUID(String mac) {
if (mac == null)
EthernetAddress eAddr = new EthernetAddress(mac);
return UUIDGenerator.getInstance().generateTimeBasedUUID(eAddr)
.toString();
e) 擷取網絡流量等資訊
publicvoid testNetIfList() throws Exception {
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");
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) {
print(e.getMessage());
void print(String msg){
System.out.println(msg);
f) 一些其他的資訊
privatevoid getEthernetInfo(){
String[] ifaces = sigar.getNetInterfaceList();
for (int i = 0; i < ifaces.length; i++) {
System.out.println("cfg.getAddress() = " + cfg.getAddress());//IP位址
System.out.println("cfg.getBroadcast() = " + cfg.getBroadcast());//網關廣播位址
System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());//網卡MAC位址
System.out.println("cfg.getNetmask() = " + cfg.getNetmask());//子網路遮罩
System.out.println("cfg.getDescription() = " + cfg.getDescription());//網卡描述資訊
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();
System.out.println("Error while creating GUID" + e);