使用Hyperic-Sigar获取服务器设备信息(监控服务器)

有时候我们要监控服务器各种设备信息,那么想要用java语言开发时,可以用Hyperic-Sigar。
Hyperic-Sigar是一个收集系统各项底层信息的工具集.他有如下特点:

收集信息全面
收集CPU,MEM,NETWORK,PROCESS,IOSTAT等
使用Sigar,你完全可以模仿出cpuinfo,meminfo,top,free,ifconfig,ipconfig,netstat,route,df,du,ps,ls等多种unix平台和windows平台的指令.
2.跨平台,支持多数平台
支持的平台包括:windows系列(32系列,IA64系列,AMD64系列),Linux系列,freeBsd系列,HPUnix系列,Sun solaris/Sparc/Sparc64系列,macOs系列,AIX系列等。

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