java如何实现系统监控、系统信息收集、sigar开源API的学习

首先给大家介绍一个开源工具Sigar 
官网:http://sigar.hyperic.com/ 
API:http://www.hyperic.com/support/docs/sigar/index-all.html(由于是英文的,英文不好的可以用谷歌浏览器的翻译功能,直接转换为简体中文进行阅读) 

Sigar(System Information Gatherer And Reporter),是一个开源的工具,提供了跨平台的系统信息收集的API,由C语言实现的。可以收集的信息包括: 

1, CPU信息,包括基本信息(vendor、model、mhz、cacheSize)和统计信息(user、sys、idle、nice、wait) 

2, 文件系统信息,包括Filesystem、Size、Used、Avail、Use%、Type 

3, 事件信息,类似Service Control Manager 

4, 内存信息,物理内存和交换内存的总数、使用数、剩余数;RAM的大小 

5, 网络信息,包括网络接口信息和网络路由信息 

6, 进程信息,包括每个进程的内存、CPU占用数、状态、参数、句柄 

7, IO信息,包括IO的状态,读写大小等 

8, 服务状态信息 

9, 系统信息,包括操作系统版本,系统资源限制情况,系统运行时间以及负载,JAVA的版本信息等. 

Sigar在Java中的使用: 
开发时将附件中sigar.rar中的所有文件及jar包放在工程的lib文件夹下。 

Java代码 复制代码 收藏代码
  1. package com.test_sigar; 
  2.  
  3. import java.net.InetAddress; 
  4. import java.net.UnknownHostException; 
  5. import java.text.DecimalFormat; 
  6.  
  7. import org.hyperic.sigar.CpuInfo; 
  8. import org.hyperic.sigar.CpuPerc; 
  9. import org.hyperic.sigar.FileSystem; 
  10. import org.hyperic.sigar.FileSystemUsage; 
  11. import org.hyperic.sigar.Mem; 
  12. import org.hyperic.sigar.NetFlags; 
  13. import org.hyperic.sigar.NetInterfaceConfig; 
  14. import org.hyperic.sigar.NetInterfaceStat; 
  15. import org.hyperic.sigar.OperatingSystem; 
  16. import org.hyperic.sigar.Sigar; 
  17. import org.hyperic.sigar.SigarException; 
  18. import org.hyperic.sigar.SigarNotImplementedException; 
  19. import org.hyperic.sigar.Swap; 
  20.  
  21. public class SysInfo { 
  22.  
  23.     public static void main(String [] args) throws Exception{ 
  24.         SysInfo s =new SysInfo(); 
  25.         System.out.println("CPU个数:"+s.getCpuCount()); 
  26.         s.getCpuTotal(); 
  27.         s.testCpuPerc(); 
  28.         s.getPhysicalMemory(); 
  29.         s.testWho(); 
  30.         s.testFileSystemInfo(); 
  31.         s.testGetOSInfo(); 
  32.     } 
  33.     /**
  34.      * 1.CPU资源信息
  35.      */ 
  36.      
  37.     // a)CPU数量(单位:个) 
  38.     public static int getCpuCount() throws SigarException { 
  39.         Sigar sigar = new Sigar(); 
  40.         try { 
  41.             return sigar.getCpuInfoList().length; 
  42.         } finally { 
  43.             sigar.close(); 
  44.         } 
  45.     } 
  46.  
  47.     // b)CPU的总量(单位:HZ)及CPU的相关信息 
  48.     public void getCpuTotal() { 
  49.         Sigar sigar = new Sigar(); 
  50.         CpuInfo[] infos; 
  51.         try { 
  52.             infos = sigar.getCpuInfoList(); 
  53.  
  54.             for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用 
  55.                 CpuInfo info = infos[i]; 
  56.                 System.out.println("CPU的总量:" + info.getMhz());// CPU的总量MHz 
  57.                 System.out.println("获得CPU的卖主:" + info.getVendor());// 获得CPU的卖主,如:Intel 
  58.                 System.out.println("CPU的类别:" + info.getModel());// 获得CPU的类别,如:Celeron 
  59.                 System.out.println("缓冲存储器数量:" + info.getCacheSize());// 缓冲存储器数量 
  60.                 System.out.println("**************"); 
  61.             } 
  62.         } catch (SigarException e) { 
  63.             e.printStackTrace(); 
  64.         } 
  65.     } 
  66.  
  67.     // c)CPU的用户使用量、系统使用剩余量、总的剩余量、总的使用占用量等(单位:100%) 
  68.     public void testCpuPerc() { 
  69.         Sigar sigar = new Sigar(); 
  70.         // 方式一,主要是针对一块CPU的情况 
  71.         CpuPerc cpu; 
  72.         try { 
  73.             cpu = sigar.getCpuPerc(); 
  74.             printCpuPerc(cpu); 
  75.         } catch (SigarException e) { 
  76.             e.printStackTrace(); 
  77.         } 
  78.         // 方式二,不管是单块CPU还是多CPU都适用 
  79.         CpuPerc cpuList[] = null
  80.         try { 
  81.             cpuList = sigar.getCpuPercList(); 
  82.         } catch (SigarException e) { 
  83.             e.printStackTrace(); 
  84.             return
  85.         } 
  86.         for (int i = 0; i < cpuList.length; i++) { 
  87.             printCpuPerc(cpuList[i]); 
  88.         } 
  89.     } 
  90.  
  91.     private void printCpuPerc(CpuPerc cpu) { 
  92.         System.out.println("用户使用率:" + CpuPerc.format(cpu.getUser()));// 用户使用率 
  93.         System.out.println("系统使用率:" + CpuPerc.format(cpu.getSys()));// 系统使用率 
  94.         System.out.println("当前等待率:" + CpuPerc.format(cpu.getWait()));// 当前等待率 
  95.         System.out.println("Nice :" + CpuPerc.format(cpu.getNice()));// 
  96.         System.out.println("当前空闲率:" + CpuPerc.format(cpu.getIdle()));// 当前空闲率 
  97.         System.out.println("总的使用率:" + CpuPerc.format(cpu.getCombined()));// 总的使用率 
  98.         System.out.println("**************"); 
  99.     } 
  100.  
  101.     /**
  102.      * 2.内存资源信息
  103.      *
  104.      */ 
  105.      
  106.     public void getPhysicalMemory() { 
  107.         // a)物理内存信息 
  108.         DecimalFormat df = new DecimalFormat("#0.00"); 
  109.         Sigar sigar = new Sigar(); 
  110.         Mem mem; 
  111.         try { 
  112.             mem = sigar.getMem(); 
  113.             // 内存总量 
  114.             System.out.println("内存总量:" + df.format((float)mem.getTotal() / 1024/1024/1024) + "G"); 
  115.             // 当前内存使用量 
  116.             System.out.println("当前内存使用量:" + df.format((float)mem.getUsed() / 1024/1024/1024) + "G"); 
  117.             // 当前内存剩余量 
  118.             System.out.println("当前内存剩余量:" + df.format((float)mem.getFree() / 1024/1024/1024) + "G"); 
  119.             // b)系统页面文件交换区信息 
  120.             Swap swap = sigar.getSwap(); 
  121.             // 交换区总量 
  122.             System.out.println("交换区总量:" + df.format((float)swap.getTotal() / 1024/1024/1024) + "G"); 
  123.             // 当前交换区使用量 
  124.             System.out.println("当前交换区使用量:" + df.format((float)swap.getUsed() / 1024/1024/1024) + "G"); 
  125.             // 当前交换区剩余量 
  126.             System.out.println("当前交换区剩余量:" + df.format((float)swap.getFree() / 1024/1024/1024) + "G"); 
  127.         } catch (SigarException e) { 
  128.             e.printStackTrace(); 
  129.         } 
  130.     } 
  131.  
  132.     /**
  133.      * 3.操作系统信息
  134.      *
  135.      */ 
  136.      
  137.     // a)取到当前操作系统的名称: 
  138.     public String getPlatformName() { 
  139.         String hostname = ""
  140.         try { 
  141.             hostname = InetAddress.getLocalHost().getHostName(); 
  142.         } catch (Exception exc) { 
  143.             Sigar sigar = new Sigar(); 
  144.             try { 
  145.                 hostname = sigar.getNetInfo().getHostName(); 
  146.             } catch (SigarException e) { 
  147.                 hostname = "localhost.unknown"
  148.             } finally { 
  149.                 sigar.close(); 
  150.             } 
  151.         } 
  152.         return hostname; 
  153.     } 
  154.  
  155.     // b)取当前操作系统的信息 
  156.     public void testGetOSInfo() { 
  157.         OperatingSystem OS = OperatingSystem.getInstance(); 
  158.         // 操作系统内核类型如: 386、486、586等x86 
  159.         System.out.println("OS.getArch() = " + OS.getArch()); 
  160.         System.out.println("OS.getCpuEndian() = " + OS.getCpuEndian());// 
  161.         System.out.println("OS.getDataModel() = " + OS.getDataModel());// 
  162.         // 系统描述 
  163.         System.out.println("OS.getDescription() = " + OS.getDescription()); 
  164.         System.out.println("OS.getMachine() = " + OS.getMachine());// 
  165.         // 操作系统类型 
  166.         System.out.println("OS.getName() = " + OS.getName()); 
  167.         System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());// 
  168.         // 操作系统的卖主 
  169.         System.out.println("OS.getVendor() = " + OS.getVendor()); 
  170.         // 卖主名称 
  171.         System.out 
  172.                 .println("OS.getVendorCodeName() = " + OS.getVendorCodeName()); 
  173.         // 操作系统名称 
  174.         System.out.println("OS.getVendorName() = " + OS.getVendorName()); 
  175.         // 操作系统卖主类型 
  176.         System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion()); 
  177.         // 操作系统的版本号 
  178.         System.out.println("OS.getVersion() = " + OS.getVersion()); 
  179.     } 
  180.  
  181.     // c)取当前系统进程表中的用户信息 
  182.     public void testWho() { 
  183.         try { 
  184.             Sigar sigar = new Sigar(); 
  185.             org.hyperic.sigar.Who[] who = sigar.getWhoList(); 
  186.             if (who != null && who.length > 0) { 
  187.                 for (int i = 0; i < who.length; i++) { 
  188.                     System.out.println("\n~~~~~~~~~" + String.valueOf(i) 
  189.                             + "~~~~~~~~~"); 
  190.                     org.hyperic.sigar.Who _who = who[i]; 
  191.                     System.out.println("获取设备getDevice() = " + _who.getDevice()); 
  192.                     System.out.println("获得主机getHost() = " + _who.getHost()); 
  193.                     System.out.println("获取的时间getTime() = " + _who.getTime()); 
  194.                     // 当前系统进程表中的用户名 
  195.                     System.out.println("获取用户getUser() = " + _who.getUser()); 
  196.                 } 
  197.             } 
  198.         } catch (SigarException e) { 
  199.             e.printStackTrace(); 
  200.         } 
  201.     } 
  202.  
  203.     // 4.资源信息(主要是硬盘) 
  204.     // a)取硬盘已有的分区及其详细信息(通过sigar.getFileSystemList()来获得FileSystem列表对象,然后对其进行编历): 
  205.     public void testFileSystemInfo() throws Exception { 
  206.         Sigar sigar = new Sigar(); 
  207.         FileSystem fslist[] = sigar.getFileSystemList(); 
  208.         DecimalFormat df = new DecimalFormat("#0.00"); 
  209.         // String dir = System.getProperty("user.home");// 当前用户文件夹路径 
  210.         for (int i = 0; i < fslist.length; i++) { 
  211.             System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~"); 
  212.             FileSystem fs = fslist[i]; 
  213.             // 分区的盘符名称 
  214.             System.out.println("fs.getDevName() = " + fs.getDevName()); 
  215.             // 分区的盘符名称 
  216.             System.out.println("fs.getDirName() = " + fs.getDirName()); 
  217.             System.out.println("fs.getFlags() = " + fs.getFlags());// 
  218.             // 文件系统类型,比如 FAT32、NTFS 
  219.             System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName()); 
  220.             // 文件系统类型名,比如本地硬盘、光驱、网络文件系统等 
  221.             System.out.println("fs.getTypeName() = " + fs.getTypeName()); 
  222.             // 文件系统类型 
  223.             System.out.println("fs.getType() = " + fs.getType()); 
  224.             FileSystemUsage usage = null
  225.             try { 
  226.                 usage = sigar.getFileSystemUsage(fs.getDirName()); 
  227.             } catch (SigarException e) { 
  228.                 if (fs.getType() == 2
  229.                     throw e; 
  230.                 continue
  231.             } 
  232.             switch (fs.getType()) { 
  233.             case 0// TYPE_UNKNOWN :未知 
  234.                 break
  235.             case 1// TYPE_NONE 
  236.                 break
  237.             case 2// TYPE_LOCAL_DISK : 本地硬盘 
  238.                 // 文件系统总大小 
  239.                 System.out.println(" Total = " + df.format((float)usage.getTotal()/1024/1024) + "G"); 
  240.                 // 文件系统剩余大小 
  241.                 System.out.println(" Free = " + df.format((float)usage.getFree()/1024/1024) + "G"); 
  242.                 // 文件系统可用大小 
  243.                 System.out.println(" Avail = " + df.format((float)usage.getAvail()/1024/1024) + "G"); 
  244.                 // 文件系统已经使用量 
  245.                 System.out.println(" Used = " + df.format((float)usage.getUsed()/1024/1024) + "G"); 
  246.                 double usePercent = usage.getUsePercent() * 100D; 
  247.                 // 文件系统资源的利用率 
  248.                 System.out.println(" Usage = " + df.format(usePercent) + "%"); 
  249.                 break
  250.             case 3:// TYPE_NETWORK :网络 
  251.                 break
  252.             case 4:// TYPE_RAM_DISK :闪存 
  253.                 break
  254.             case 5:// TYPE_CDROM :光驱 
  255.                 break
  256.             case 6:// TYPE_SWAP :页面交换 
  257.                 break
  258.             } 
  259.             System.out.println(" DiskReads = " + usage.getDiskReads()); 
  260.             System.out.println(" DiskWrites = " + usage.getDiskWrites()); 
  261.         } 
  262.         return
  263.     } 
  264.  
  265.     // 5.网络信息 
  266.     // a)当前机器的正式域名 
  267.     public String getFQDN() { 
  268.         Sigar sigar = null
  269.         try { 
  270.             return InetAddress.getLocalHost().getCanonicalHostName(); 
  271.         } catch (UnknownHostException e) { 
  272.             try { 
  273.                 sigar = new Sigar(); 
  274.                 return sigar.getFQDN(); 
  275.             } catch (SigarException ex) { 
  276.                 return null
  277.             } finally { 
  278.                 sigar.close(); 
  279.             } 
  280.         } 
  281.     } 
  282.  
  283.     // b)取到当前机器的IP地址 
  284.     public String getDefaultIpAddress() { 
  285.         String address = null
  286.         try { 
  287.             address = InetAddress.getLocalHost().getHostAddress(); 
  288.             // 没有出现异常而正常当取到的IP时,如果取到的不是网卡循回地址时就返回 
  289.             // 否则再通过Sigar工具包中的方法来获取 
  290.             if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) { 
  291.                 return address; 
  292.             } 
  293.         } catch (UnknownHostException e) { 
  294.             // hostname not in DNS or /etc/hosts 
  295.         } 
  296.         Sigar sigar = new Sigar(); 
  297.         try { 
  298.             address = sigar.getNetInterfaceConfig().getAddress(); 
  299.         } catch (SigarException e) { 
  300.             address = NetFlags.LOOPBACK_ADDRESS; 
  301.         } finally { 
  302.             sigar.close(); 
  303.         } 
  304.         return address; 
  305.     } 
  306.  
  307.     // c)取到当前机器的MAC地址 
  308.     public String getMAC() { 
  309.         Sigar sigar = null
  310.         try { 
  311.             sigar = new Sigar(); 
  312.             String[] ifaces = sigar.getNetInterfaceList(); 
  313.             String hwaddr = null
  314.             for (int i = 0; i < ifaces.length; i++) { 
  315.                 NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]); 
  316.                 if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) 
  317.                         || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0 
  318.                         || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) { 
  319.                     continue
  320.                 } 
  321.                 /*
  322.                  * 如果存在多张网卡包括虚拟机的网卡,默认只取第一张网卡的MAC地址,如果要返回所有的网卡(包括物理的和虚拟的)则可以修改方法的返回类型为数组或Collection
  323.                  * ,通过在for循环里取到的多个MAC地址。
  324.                  */ 
  325.                 hwaddr = cfg.getHwaddr(); 
  326.                 break
  327.             } 
  328.             return hwaddr != null ? hwaddr : null
  329.         } catch (Exception e) { 
  330.             return null
  331.         } finally { 
  332.             if (sigar != null
  333.                 sigar.close(); 
  334.         } 
  335.     } 
  336.  
  337.     // d)获取网络流量等信息 
  338.     public void testNetIfList() throws Exception { 
  339.         Sigar sigar = new Sigar(); 
  340.         String ifNames[] = sigar.getNetInterfaceList(); 
  341.         for (int i = 0; i < ifNames.length; i++) { 
  342.             String name = ifNames[i]; 
  343.             NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name); 
  344.             print("\nname = " + name);// 网络设备名 
  345.             print("Address = " + ifconfig.getAddress());// IP地址 
  346.             print("Netmask = " + ifconfig.getNetmask());// 子网掩码 
  347.             if ((ifconfig.getFlags() & 1L) <= 0L) { 
  348.                 print("!IFF_UP...skipping getNetInterfaceStat"); 
  349.                 continue
  350.             } 
  351.             try { 
  352.                 NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name); 
  353.                 print("RxPackets = " + ifstat.getRxPackets());// 接收的总包裹数 
  354.                 print("TxPackets = " + ifstat.getTxPackets());// 发送的总包裹数 
  355.                 print("RxBytes = " + ifstat.getRxBytes());// 接收到的总字节数 
  356.                 print("TxBytes = " + ifstat.getTxBytes());// 发送的总字节数 
  357.                 print("RxErrors = " + ifstat.getRxErrors());// 接收到的错误包数 
  358.                 print("TxErrors = " + ifstat.getTxErrors());// 发送数据包时的错误数 
  359.                 print("RxDropped = " + ifstat.getRxDropped());// 接收时丢弃的包数 
  360.                 print("TxDropped = " + ifstat.getTxDropped());// 发送时丢弃的包数 
  361.             } catch (SigarNotImplementedException e) { 
  362.             } catch (SigarException e) { 
  363.                 print(e.getMessage()); 
  364.             } 
  365.         } 
  366.     } 
  367.  
  368.     void print(String msg) { 
  369.         System.out.println(msg); 
  370.     } 
  371.  
  372.     // e)一些其他的信息 
  373.     public void getEthernetInfo() { 
  374.         Sigar sigar = null
  375.         try { 
  376.             sigar = new Sigar(); 
  377.             String[] ifaces = sigar.getNetInterfaceList(); 
  378.             for (int i = 0; i < ifaces.length; i++) { 
  379.                 NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]); 
  380.                 if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) 
  381.                         || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0 
  382.                         || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) { 
  383.                     continue
  384.                 } 
  385.                 System.out.println("cfg.getAddress() = " + cfg.getAddress());// IP地址 
  386.                 System.out 
  387.                         .println("cfg.getBroadcast() = " + cfg.getBroadcast());// 网关广播地址 
  388.                 System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());// 网卡MAC地址 
  389.                 System.out.println("cfg.getNetmask() = " + cfg.getNetmask());// 子网掩码 
  390.                 System.out.println("cfg.getDescription() = " 
  391.                         + cfg.getDescription());// 网卡描述信息 
  392.                 System.out.println("cfg.getType() = " + cfg.getType());// 
  393.                 System.out.println("cfg.getDestination() = " 
  394.                         + cfg.getDestination()); 
  395.                 System.out.println("cfg.getFlags() = " + cfg.getFlags());// 
  396.                 System.out.println("cfg.getMetric() = " + cfg.getMetric()); 
  397.                 System.out.println("cfg.getMtu() = " + cfg.getMtu()); 
  398.                 System.out.println("cfg.getName() = " + cfg.getName()); 
  399.                 System.out.println(); 
  400.             } 
  401.         } catch (Exception e) { 
  402.             System.out.println("Error while creating GUID" + e); 
  403.         } finally { 
  404.             if (sigar != null
  405.                 sigar.close(); 
  406.         } 
  407.     } 
  408.  

posted on 2013-12-25 15:07  hawen  阅读(844)  评论(0编辑  收藏  举报

导航