【深入JAVA】Java中獲取系統相關信息——sigar

在閱讀的過程中有任何問題,歡迎一起交流

郵箱:[email protected]   

QQ:1494713801

 

 

一、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信息代碼  收藏代碼
  1. // CPU數量(單位:個)  
  2. int cpuLength = sigar.getCpuInfoList().length;  
  3. print(cpuLength);  
  4.   
  5. // CPU的總量(單位:HZ)及CPU的相關信息  
  6. CpuInfo infos[] = sigar.getCpuInfoList();  
  7. for (int i = 0; i < infos.length; i++) {// 不管是單塊CPU還是多CPU都適用  
  8.     CpuInfo info = infos[i];  
  9.     print("mhz=" + info.getMhz());// CPU的總量MHz  
  10.     print("vendor=" + info.getVendor());// 獲得CPU的賣主,如:Intel  
  11.     print("model=" + info.getModel());// 獲得CPU的類別,如:Celeron  
  12.     print("cache size=" + info.getCacheSize());// 緩衝存儲器數量  
  13. }  
  14.   
  15.   
  16. // 方式一,主要是針對一塊CPU的情況  
  17. CpuPerc cpu;  
  18. try {  
  19.     cpu = sigar.getCpuPerc();  
  20.     printCpuPerc(cpu);  
  21. } catch (SigarException e) {  
  22.     e.printStackTrace();  
  23. }  
  24.   
  25. // 方式二,不管是單塊CPU還是多CPU都適用  
  26. CpuPerc cpuList[] = null;  
  27. try {  
  28.     cpuList = sigar.getCpuPercList();  
  29. } catch (SigarException e) {  
  30.     e.printStackTrace();  
  31. }  
  32. for (int i = 0; i < cpuList.length; i++) {  
  33.     // printCpuPerc(cpuList[i]);  
  34. }  

 

 

 

 

獲取內存信息代碼  收藏代碼
  1. // 物理內存信息  
  2. Mem mem = sigar.getMem();  
  3. // 內存總量  
  4. print("Total = " + mem.getTotal() / 1024L / 1024 + "M av");  
  5. // 當前內存使用量  
  6. print("Used = " + mem.getUsed() / 1024L / 1024 + "M used");  
  7. // 當前內存剩餘量  
  8. print("Free = " + mem.getFree() / 1024L / 1024 + "M free");  
  9.   
  10. // 系統頁面文件交換區信息  
  11. Swap swap = sigar.getSwap();  
  12. // 交換區總量  
  13. print("Total = " + swap.getTotal() / 1024L + "K av");  
  14. // 當前交換區使用量  
  15. print("Used = " + swap.getUsed() / 1024L + "K used");  
  16. // 當前交換區剩餘量  
  17. print("Free = " + swap.getFree() / 1024L + "K free");  

 

 

 

 

獲取操作系統信息代碼  收藏代碼
  1. "white-space: normal; background-color: #ffffff;""white-space: normal; background-color: #ffffff;">// 取到當前操作系統的名稱  
  2. String hostname = "";  
  3. try {  
  4.     hostname = InetAddress.getLocalHost().getHostName();  
  5. } catch (Exception exc) {  
  6.     try {  
  7.         hostname = sigar.getNetInfo().getHostName();  
  8.     } catch (SigarException e) {  
  9.         hostname = "localhost.unknown";  
  10.     } finally {  
  11.         sigar.close();  
  12.     }  
  13. }  
  14. print(hostname);  
  15.   
  16. // 取當前操作系統的信息  
  17. OperatingSystem OS = OperatingSystem.getInstance();  
  18. // 操作系統內核類型如: 386486586等x86  
  19. print("OS.getArch() = " + OS.getArch());  
  20. print("OS.getCpuEndian() = " + OS.getCpuEndian());//  
  21. print("OS.getDataModel() = " + OS.getDataModel());//  
  22. // 系統描述  
  23. print("OS.getDescription() = " + OS.getDescription());  
  24. print("OS.getMachine() = " + OS.getMachine());//  
  25. // 操作系統類型  
  26. print("OS.getName() = " + OS.getName());  
  27. print("OS.getPatchLevel() = " + OS.getPatchLevel());//  
  28. // 操作系統的賣主  
  29. print("OS.getVendor() = " + OS.getVendor());  
  30. // 賣主名稱  
  31. System.out  
  32.         .println("OS.getVendorCodeName() = " + OS.getVendorCodeName());  
  33. // 操作系統名稱  
  34. print("OS.getVendorName() = " + OS.getVendorName());  
  35. // 操作系統賣主類型  
  36. print("OS.getVendorVersion() = " + OS.getVendorVersion());  
  37. // 操作系統的版本號  
  38. print("OS.getVersion() = " + OS.getVersion());  
  39.   
  40. // 取當前系統進程表中的用戶信息  
  41. Who who[] = sigar.getWhoList();  
  42. if (who != null && who.length > 0) {  
  43.     for (int i = 0; i < who.length; i++) {  
  44.         print("\n~~~~~~~~~" + String.valueOf(i) + "~~~~~~~~~");  
  45.         Who _who = who[i];  
  46.         print("getDevice() = " + _who.getDevice());  
  47.         print("getHost() = " + _who.getHost());  
  48.         print("getTime() = " + _who.getTime());  
  49.         // 當前系統進程表中的用戶名  
  50.         print("getUser() = " + _who.getUser());  
  51.     }  
  52. }  

 

 

 

獲取磁盤信息代碼  收藏代碼
  1. "white-space: normal; background-color: #ffffff;">// 取硬盤已有的分區及其詳細信息(通過sigar.getFileSystemList()來獲得FileSystem列表對象,然後對其進行編歷  
  2. FileSystem fslist[] = sigar.getFileSystemList();  
  3. String dir = System.getProperty("user.home");// 當前用戶文件夾路徑  
  4. print(dir + "   " + fslist.length);  
  5. for (int i = 0; i < fslist.length; i++) {  
  6.     print("\n~~~~~~~~~~" + i + "~~~~~~~~~~");  
  7. FileSystem fs = fslist[i];  
  8. // 分區的盤符名稱  
  9. print("fs.getDevName() = " + fs.getDevName());  
  10. // 分區的盤符名稱  
  11. print("fs.getDirName() = " + fs.getDirName());  
  12. print("fs.getFlags() = " + fs.getFlags());//  
  13. // 文件系統類型,比如 FAT32、NTFS  
  14. print("fs.getSysTypeName() = " + fs.getSysTypeName());  
  15. // 文件系統類型名,比如本地硬盤、光驅、網絡文件系統等  
  16. print("fs.getTypeName() = " + fs.getTypeName());  
  17. // 文件系統類型  
  18. print("fs.getType() = " + fs.getType());  
  19. FileSystemUsage usage = null;  
  20. try {  
  21.     usage = sigar.getFileSystemUsage(fs.getDirName());  
  22. } catch (SigarException e) {  
  23.     if (fs.getType() == 2)  
  24.         throw e;  
  25.     continue;  
  26. }  
  27. switch (fs.getType()) {  
  28. case 0: // TYPE_UNKNOWN :未知  
  29.     break;  
  30. case 1: // TYPE_NONE  
  31.     break;  
  32. case 2: // TYPE_LOCAL_DISK : 本地硬盤  
  33.     // 文件系統總大小  
  34.     print(" Total = " + usage.getTotal() + "KB");  
  35.     // 文件系統剩餘大小  
  36.     print(" Free = " + usage.getFree() + "KB");  
  37.     // 文件系統可用大小  
  38.     print(" Avail = " + usage.getAvail() + "KB");  
  39.     // 文件系統已經使用量  
  40.     print(" Used = " + usage.getUsed() + "KB");  
  41.     double usePercent = usage.getUsePercent() * 100D;  
  42.     // 文件系統資源的利用率  
  43.     print(" Usage = " + usePercent + "%");  
  44.     break;  
  45. case 3:// TYPE_NETWORK :網絡  
  46.     break;  
  47. case 4:// TYPE_RAM_DISK :閃存  
  48.     break;  
  49. case 5:// TYPE_CDROM :光驅  
  50.     break;  
  51. case 6:// TYPE_SWAP :頁面交換  
  52.     break;  
  53. }  
  54. print(" DiskReads = " + usage.getDiskReads());  
  55. print(" DiskWrites = " + usage.getDiskWrites());  
  56. }  

 

 

 

獲取網絡信息代碼  收藏代碼
  1. "white-space: normal; background-color: #ffffff;"> // 當前機器的正式域名  
  2. try {  
  3.     print(InetAddress.getLocalHost().getCanonicalHostName());  
  4. } catch (UnknownHostException e) {  
  5.     try {  
  6.         print(sigar.getFQDN());  
  7.     } catch (SigarException ex) {  
  8.     } finally {  
  9.         sigar.close();  
  10.     }  
  11. }  
  12.   
  13. // 取到當前機器的IP地址  
  14. String address = null;  
  15. try {  
  16.     address = InetAddress.getLocalHost().getHostAddress();  
  17.     // 沒有出現異常而正常當取到的IP時,如果取到的不是網卡循回地址時就返回  
  18.     // 否則再通過Sigar工具包中的方法來獲取  
  19.     print(address);  
  20.     if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) {  
  21.     }  
  22. } catch (UnknownHostException e) {  
  23.     // hostname not in DNS or /etc/hosts  
  24. }  
  25. try {  
  26.     address = sigar.getNetInterfaceConfig().getAddress();  
  27. } catch (SigarException e) {  
  28.     address = NetFlags.LOOPBACK_ADDRESS;  
  29. } finally {  
  30. }  
  31. print(address);  
  32.   
  33. // 取到當前機器的MAC地址  
  34. String[] ifaces = sigar.getNetInterfaceList();  
  35. String hwaddr = null;  
  36. for (int i = 0; i < ifaces.length; i++) {  
  37.     NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);  
  38.     if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())  
  39.             || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0  
  40.             || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {  
  41.         continue;  
  42.     }  
  43.     hwaddr = cfg.getHwaddr();  
  44.     print(hwaddr);  
  45.     // break;  
  46. }  
  47. print(hwaddr != null ? hwaddr : null);  
  48.   
  49. // 獲取網絡流量等信息  
  50. String ifNames[] = sigar.getNetInterfaceList();  
  51. for (int i = 0; i < ifNames.length; i++) {  
  52.     String name = ifNames[i];  
  53.     NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);  
  54.     print("\nname = " + name);// 網絡設備名  
  55.     print("Address = " + ifconfig.getAddress());// IP地址  
  56.     print("Netmask = " + ifconfig.getNetmask());// 子網掩碼  
  57.     if ((ifconfig.getFlags() & 1L) <= 0L) {  
  58.         print("!IFF_UP...skipping getNetInterfaceStat");  
  59.         continue;  
  60.     }  
  61.     try {  
  62.         NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);  
  63.         print("RxPackets = " + ifstat.getRxPackets());// 接收的總包裹數  
  64.         print("TxPackets = " + ifstat.getTxPackets());// 發送的總包裹數  
  65.         print("RxBytes = " + ifstat.getRxBytes());// 接收到的總字節數  
  66.         print("TxBytes = " + ifstat.getTxBytes());// 發送的總字節數  
  67.         print("RxErrors = " + ifstat.getRxErrors());// 接收到的錯誤包數  
  68.         print("TxErrors = " + ifstat.getTxErrors());// 發送數據包時的錯誤數  
  69.         print("RxDropped = " + ifstat.getRxDropped());// 接收時丟棄的包數  
  70.         print("TxDropped = " + ifstat.getTxDropped());// 發送時丟棄的包數  
  71.     } catch (SigarNotImplementedException e) {  
  72.     } catch (SigarException e) {  
  73.         print(e.getMessage());  
  74.     }  
  75. }  
  76.   
  77. // 一些其他的信息  
  78. for (int i = 0; i < ifaces.length; i++) {  
  79.     NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);  
  80.     if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())  
  81.             || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0  
  82.             || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {  
  83.         continue;  
  84.     }  
  85.     print("cfg.getAddress() = " + cfg.getAddress());// IP地址  
  86.     print("cfg.getBroadcast() = " + cfg.getBroadcast());// 網關廣播地址  
  87.     print("cfg.getHwaddr() = " + cfg.getHwaddr());// 網卡MAC地址  
  88.     print("cfg.getNetmask() = " + cfg.getNetmask());// 子網掩碼  
  89.     System.out  
  90.             .println("cfg.getDescription() = " + cfg.getDescription());// 網卡描述信息  
  91.     print("cfg.getType() = " + cfg.getType());//  
  92.     System.out  
  93.             .println("cfg.getDestination() = " + cfg.getDestination());  
  94.     print("cfg.getFlags() = " + cfg.getFlags());//  
  95.     print("cfg.getMetric() = " + cfg.getMetric());  
  96.     print("cfg.getMtu() = " + cfg.getMtu());  
  97.     print("cfg.getName() = " + cfg.getName());  
  98. }  

 

三、sigar的包及相關文件

 該類需要引入jar包,進入下載

另外爲了防止程序運行時的錯誤,還需要相關文件,進入下載

四、在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文件夾下

 

附:代碼轉自http://blog.sina.com.cn/s/blog_5017ea6c0101byrr.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章