snmp4j介绍及api使用

一、SNMP简介

SNMP指的是简单网络管理协议。它属于TCP/IP五层协议中的应用层协议。它提供了一种简单和方便的模式来管理网络中的各个元素。这里的元素就是各个被管理的对象,可以是因特网中的某个硬件,比如网卡,也可以是某些硬件和软件的配置参数的集合。由于SNMP协议简单可靠 ,受到了众多厂商的欢迎,成为了目前最为广泛的网管协议。

SNMP协议主要由两大部分构成:SNMP管理站和SNMP代理。SNMP管理站是一个中心节点,负责收集维护各个SNMP元素的信息,并对这些信息进行处理,最后反馈给网络管理员;而SNMP代理是运行在各个被管理的网络节点之上,负责统计该节点的各项信息,并且负责与SNMP管理站交互,接收并执行管理站的命令,上传各种本地的网络信息。

SNMP管理站和SNMP代理之间是松散耦合。他们之间的通信是通过UDP协议完成的。一般情况下,SNMP管理站通过UDP协议向SNMP代理发送各种命令,当SNMP代理收到命令后,返回SNMP管理站需要的参数。但是当SNMP代理检测到网络元素异常的时候,也可以主动向SNMP管理站发送消息,通告当前异常状况。

SNMP协议于1988年发布。到目前一共经历了V1V2V3三个版本。其中V1已经被废弃,而V2c虽然没有能够成为正式标准,但是已经被很多厂家所接受,V3目前是因特网的正式标准。与V1相比,V2V3更能适应大规模的网络管理,而且在安全方面有了较大的改进。

二一、Win7开启SNMP服务 

通过SNMP监控Windows主机需要在被监控的服务器上安装简单网络管理协议(SNMP)的Windows组件,以Windows 7系统为例:
首先,在控制面板中找到“卸载程序”;


在弹出的窗口中单击“打开或关闭Windows功能”;

 

勾选弹出窗口中的“简单网络管理协议(SNMP)”项后单击“确定”并根据提示完成安装即可。

 

完成SNMP服务的安装后,右键单击“计算机”选择“管理”

 


在弹出的“计算机管理”窗口中左侧导航栏中找到“服务”,并在右侧找到“SNMP Service”项;

 

鼠标双击“SNMP Service”选项,在弹出的窗口中切换到“安全”选项卡中,如上图添加“接受的社区名称”和接收那些主机发出的SNMP数据包。

 

“接受的社区名称”是自己定义的任意字符都可以,接收那些主机发出的SNMP数据包定义成你的Nagios服务器即可。到这里被监控端的Windows主机的SNMP服务就配置完成了。


二二、Linux


1、检查是否有SNMP服务,若没有,请先安装

service snmpd status  #查看是否安装snmp

yum install -y net-snmp* #若没安装,则安装

2、先编辑Snmp的配置文件,设置安全的验证方式

vi /etc/snmp/snmpd.conf

3、设置完毕,开关SNMP

service snmpd start

service snmpd stop

 

4、设置SNMP开机自动启动

chkconfig snmpd on

chkconfig snmpd off

5、增强的SNMP安全性

/etc/sysconfig/iptables 中

iptables -A INPUT  -p udp -s 192.168.2.18 --dport 161 -j ACCEPT

service iptables save

以上做的目的,就是只让指定的监控服务器(IP)才能与您的SNMP服务建立连接。

 

三、snmp4j例子

准备工作:snmp4j的jar包可以在它的官方网站http://www.snmp4j.org/上下载

1、获取CPU利用率方法

[java]  view plain  copy
  1. //获取cpu使用率  
  2. public static void collectCPU() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] oids = {"1.3.6.1.2.1.25.3.3.1.2"};  
  7. try {  
  8. transport = new DefaultUdpTransportMapping();  
  9. snmp = new Snmp(transport);//创建snmp  
  10. snmp.listen();//监听消息  
  11. target = new CommunityTarget();  
  12. target.setCommunity(new OctetString("public"));  
  13. target.setRetries(2);  
  14. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  15. target.setTimeout(8000);  
  16. target.setVersion(SnmpConstants.version2c);  
  17. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  18. @Override  
  19. public PDU createPDU(Target arg0) {  
  20. PDU request = new PDU();  
  21. request.setType(PDU.GET);  
  22. return request;  
  23. }  
  24. });  
  25. OID[] columns = new OID[oids.length];  
  26. for (int i = 0; i < oids.length; i++)  
  27. columns[i] = new OID(oids[i]);  
  28. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  29. if(list.size()==1 && list.get(0).getColumns()==null){  
  30. System.out.println(" null");  
  31. }else{  
  32. int percentage = 0;  
  33. for(TableEvent event : list){  
  34. VariableBinding[] values = event.getColumns();  
  35. if(values != null)   
  36. percentage += Integer.parseInt(values[0].getVariable().toString());  
  37. }  
  38. System.out.println("CPU利用率为:"+percentage/list.size()+"%");  
  39. }  
  40. catch(Exception e){  
  41. e.printStackTrace();  
  42. }finally{  
  43. try {  
  44. if(transport!=null)  
  45. transport.close();  
  46. if(snmp!=null)  
  47. snmp.close();  
  48. catch (IOException e) {  
  49. e.printStackTrace();  
  50. }  
  51. }  
  52. }  


2、获取内存信息方法

[java]  view plain  copy
  1. //获取内存相关信息  
  2. public static void collectMemory() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] oids = {"1.3.6.1.2.1.25.2.3.1.2",  //type 存储单元类型  
  7.      "1.3.6.1.2.1.25.2.3.1.3",  //descr  
  8.      "1.3.6.1.2.1.25.2.3.1.4",  //unit 存储单元大小  
  9.      "1.3.6.1.2.1.25.2.3.1.5",  //size 总存储单元数  
  10.      "1.3.6.1.2.1.25.2.3.1.6"}; //used 使用存储单元数;  
  11. String PHYSICAL_MEMORY_OID = "1.3.6.1.2.1.25.2.1.2";//物理存储  
  12. String VIRTUAL_MEMORY_OID = "1.3.6.1.2.1.25.2.1.3"//虚拟存储  
  13. try {  
  14. transport = new DefaultUdpTransportMapping();  
  15. snmp = new Snmp(transport);//创建snmp  
  16. snmp.listen();//监听消息  
  17. target = new CommunityTarget();  
  18. target.setCommunity(new OctetString("public"));  
  19. target.setRetries(2);  
  20. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  21. target.setTimeout(8000);  
  22. target.setVersion(SnmpConstants.version2c);  
  23. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  24. @Override  
  25. public PDU createPDU(Target arg0) {  
  26. PDU request = new PDU();  
  27. request.setType(PDU.GET);  
  28. return request;  
  29. }  
  30. });  
  31. OID[] columns = new OID[oids.length];  
  32. for (int i = 0; i < oids.length; i++)  
  33. columns[i] = new OID(oids[i]);  
  34. @SuppressWarnings("unchecked")  
  35. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  36. if(list.size()==1 && list.get(0).getColumns()==null){  
  37. System.out.println(" null");  
  38. }else{  
  39. for(TableEvent event : list){  
  40. VariableBinding[] values = event.getColumns();  
  41. if(values == nullcontinue;  
  42. int unit = Integer.parseInt(values[2].getVariable().toString());//unit 存储单元大小  
  43. int totalSize = Integer.parseInt(values[3].getVariable().toString());//size 总存储单元数  
  44. int usedSize = Integer.parseInt(values[4].getVariable().toString());//used  使用存储单元数  
  45. String oid = values[0].getVariable().toString();  
  46. if (PHYSICAL_MEMORY_OID.equals(oid)){  
  47. System.out.println("PHYSICAL_MEMORY----->物理内存大小:"+(long)totalSize * unit/(1024*1024*1024)+"G   内存使用率为:"+(long)usedSize*100/totalSize+"%");  
  48. }else if (VIRTUAL_MEMORY_OID.equals(oid)) {  
  49. System.out.println("VIRTUAL_MEMORY----->虚拟内存大小:"+(long)totalSize * unit/(1024*1024*1024)+"G   内存使用率为:"+(long)usedSize*100/totalSize+"%");  
  50. }  
  51. }  
  52. }  
  53. catch(Exception e){  
  54. e.printStackTrace();  
  55. }finally{  
  56. try {  
  57. if(transport!=null)  
  58. transport.close();  
  59. if(snmp!=null)  
  60. snmp.close();  
  61. catch (IOException e) {  
  62. e.printStackTrace();  
  63. }  
  64. }  
  65. }  


 

3、获取磁盘信息方法

[java]  view plain  copy
  1. //获取磁盘相关信息  
  2. public static void collectDisk() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String DISK_OID = "1.3.6.1.2.1.25.2.1.4";  
  7. String[] oids = {"1.3.6.1.2.1.25.2.3.1.2",  //type 存储单元类型  
  8.      "1.3.6.1.2.1.25.2.3.1.3",  //descr  
  9.      "1.3.6.1.2.1.25.2.3.1.4",  //unit 存储单元大小  
  10.      "1.3.6.1.2.1.25.2.3.1.5",  //size 总存储单元数  
  11.      "1.3.6.1.2.1.25.2.3.1.6"}; //used 使用存储单元数;  
  12. try {  
  13. transport = new DefaultUdpTransportMapping();  
  14. snmp = new Snmp(transport);//创建snmp  
  15. snmp.listen();//监听消息  
  16. target = new CommunityTarget();  
  17. target.setCommunity(new OctetString("public"));  
  18. target.setRetries(2);  
  19. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  20. target.setTimeout(8000);  
  21. target.setVersion(SnmpConstants.version2c);  
  22. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  23. @Override  
  24. public PDU createPDU(Target arg0) {  
  25. PDU request = new PDU();  
  26. request.setType(PDU.GET);  
  27. return request;  
  28. }  
  29. });  
  30. OID[] columns = new OID[oids.length];  
  31. for (int i = 0; i < oids.length; i++)  
  32. columns[i] = new OID(oids[i]);  
  33. @SuppressWarnings("unchecked")  
  34. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  35. if(list.size()==1 && list.get(0).getColumns()==null){  
  36. System.out.println(" null");  
  37. }else{  
  38. for(TableEvent event : list){  
  39. VariableBinding[] values = event.getColumns();  
  40. if(values == null ||!DISK_OID.equals(values[0].getVariable().toString()))   
  41. continue;  
  42. int unit = Integer.parseInt(values[2].getVariable().toString());//unit 存储单元大小  
  43. int totalSize = Integer.parseInt(values[3].getVariable().toString());//size 总存储单元数  
  44. int usedSize = Integer.parseInt(values[4].getVariable().toString());//used  使用存储单元数  
  45. System.out.println(getChinese(values[1].getVariable().toString())+"   磁盘大小:"+(long)totalSize*unit/(1024*1024*1024)+"G   磁盘使用率为:"+(long)usedSize*100/totalSize+"%");  
  46. }  
  47. }  
  48. catch(Exception e){  
  49. e.printStackTrace();  
  50. }finally{  
  51. try {  
  52. if(transport!=null)  
  53. transport.close();  
  54. if(snmp!=null)  
  55. snmp.close();  
  56. catch (IOException e) {  
  57. e.printStackTrace();  
  58. }  
  59. }  
  60. }  


4、获取服务器进程信息方法

[java]  view plain  copy
  1. //服务器进程集合信息  
  2. public static void collectProcess() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] oids =  
  7. {"1.3.6.1.2.1.25.4.2.1.1",  //index  
  8.             "1.3.6.1.2.1.25.4.2.1.2",  //name  
  9.             "1.3.6.1.2.1.25.4.2.1.4",  //run path  
  10.      "1.3.6.1.2.1.25.4.2.1.6",  //type  
  11.      "1.3.6.1.2.1.25.5.1.1.1",  //cpu  
  12.      "1.3.6.1.2.1.25.5.1.1.2"}; //memory    
  13. try {  
  14. transport = new DefaultUdpTransportMapping();  
  15. snmp = new Snmp(transport);  
  16. snmp.listen();  
  17. target = new CommunityTarget();  
  18. target.setCommunity(new OctetString("public"));  
  19. target.setRetries(2);  
  20. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  21. target.setTimeout(8000);  
  22. target.setVersion(SnmpConstants.version2c);  
  23. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  24. @Override  
  25. public PDU createPDU(Target arg0) {  
  26. PDU request = new PDU();  
  27. request.setType(PDU.GET);  
  28. return request;  
  29. }  
  30. });  
  31. OID[] columns = new OID[oids.length];  
  32. for (int i = 0; i < oids.length; i++)  
  33. columns[i] = new OID(oids[i]);  
  34. @SuppressWarnings("unchecked")  
  35. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  36. if(list.size()==1 && list.get(0).getColumns()==null){  
  37. System.out.println(" null");  
  38. }else{  
  39. for(TableEvent event : list){  
  40. VariableBinding[] values = event.getColumns();  
  41. if(values == nullcontinue;  
  42. String name = values[1].getVariable().toString();//name  
  43. String cpu = values[4].getVariable().toString();//cpu  
  44. String memory = values[5].getVariable().toString();//memory  
  45. String path = values[2].getVariable().toString();//path  
  46. System.out.println("name--->"+name+"  cpu--->"+cpu+"  memory--->"+memory+"  path--->"+path);  
  47. }  
  48. }  
  49. catch(Exception e){  
  50. e.printStackTrace();  
  51. }finally{  
  52. try {  
  53. if(transport!=null)  
  54. transport.close();  
  55. if(snmp!=null)  
  56. snmp.close();  
  57. catch (IOException e) {  
  58. e.printStackTrace();  
  59. }  
  60. }  
  61. }  


5、获取服务器系统服务方法

[java]  view plain  copy
  1. //服务器系统服务集合  
  2. public static void collectService() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] oids =  
  7. {"1.3.6.1.4.1.77.1.2.3.1.1"};  
  8. try {  
  9. transport = new DefaultUdpTransportMapping();  
  10. snmp = new Snmp(transport);  
  11. snmp.listen();  
  12. target = new CommunityTarget();  
  13. target.setCommunity(new OctetString("public"));  
  14. target.setRetries(2);  
  15. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  16. target.setTimeout(8000);  
  17. target.setVersion(SnmpConstants.version2c);  
  18. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  19. @Override  
  20. public PDU createPDU(Target arg0) {  
  21. PDU request = new PDU();  
  22. request.setType(PDU.GET);  
  23. return request;  
  24. }  
  25. });  
  26. OID[] columns = new OID[oids.length];  
  27. for (int i = 0; i < oids.length; i++)  
  28. columns[i] = new OID(oids[i]);  
  29. @SuppressWarnings("unchecked")  
  30. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  31. if(list.size()==1 && list.get(0).getColumns()==null){  
  32. System.out.println(" null");  
  33. }else{  
  34. for(TableEvent event : list){  
  35. VariableBinding[] values = event.getColumns();  
  36. if(values == nullcontinue;  
  37. String name = values[0].getVariable().toString();//name  
  38. System.out.println("名称--->"+getChinese(name));//中文乱码,需要转为utf-8编码  
  39. }  
  40. }  
  41. catch(Exception e){  
  42. e.printStackTrace();  
  43. }finally{  
  44. try {  
  45. if(transport!=null)  
  46. transport.close();  
  47. if(snmp!=null)  
  48. snmp.close();  
  49. catch (IOException e) {  
  50. e.printStackTrace();  
  51. }  
  52. }  
  53. }  


6、获取接口信息方法

[java]  view plain  copy
  1. //服务器接口集合  
  2. public static void collectInterface() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] IF_OIDS =   
  7.     {"1.3.6.1.2.1.2.2.1.1",  //Index   
  8.      "1.3.6.1.2.1.2.2.1.2",  //descr  
  9.      "1.3.6.1.2.1.2.2.1.3",  //type  
  10.      "1.3.6.1.2.1.2.2.1.5",  //speed  
  11.      "1.3.6.1.2.1.2.2.1.6",  //mac  
  12.      "1.3.6.1.2.1.2.2.1.7",  //adminStatus  
  13.      "1.3.6.1.2.1.2.2.1.8",  //operStatus     
  14.         
  15.      "1.3.6.1.2.1.2.2.1.10"//inOctets  
  16.      "1.3.6.1.2.1.2.2.1.16"//outOctets  
  17.      "1.3.6.1.2.1.2.2.1.14"//inError  
  18.      "1.3.6.1.2.1.2.2.1.20"//outError  
  19.      "1.3.6.1.2.1.2.2.1.13"//inDiscard  
  20.      "1.3.6.1.2.1.2.2.1.19"//outDiscard  
  21.      "1.3.6.1.2.1.2.2.1.11"//inUcastPkts  
  22.      "1.3.6.1.2.1.2.2.1.17"//outUcastPkts  
  23.      "1.3.6.1.2.1.2.2.1.12"//inNUcastPkts       
  24.      "1.3.6.1.2.1.2.2.1.18"};//outNUcastPkts  
  25. String[] IP_OIDS =     
  26.     {"1.3.6.1.2.1.4.20.1.1"//ipAdEntAddr  
  27.      "1.3.6.1.2.1.4.20.1.2"//ipAdEntIfIndex  
  28.      "1.3.6.1.2.1.4.20.1.3"};//ipAdEntNetMask   
  29. try {  
  30. transport = new DefaultUdpTransportMapping();  
  31. snmp = new Snmp(transport);  
  32. snmp.listen();  
  33. target = new CommunityTarget();  
  34. target.setCommunity(new OctetString("public"));  
  35. target.setRetries(2);  
  36. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  37. target.setTimeout(8000);  
  38. target.setVersion(SnmpConstants.version2c);  
  39. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  40. @Override  
  41. public PDU createPDU(Target arg0) {  
  42. PDU request = new PDU();  
  43. request.setType(PDU.GET);  
  44. return request;  
  45. }  
  46. });  
  47. OID[] columns = new OID[IF_OIDS.length];  
  48. for (int i = 0; i < IF_OIDS.length; i++)  
  49. columns[i] = new OID(IF_OIDS[i]);  
  50. @SuppressWarnings("unchecked")  
  51. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  52. if(list.size()==1 && list.get(0).getColumns()==null){  
  53. System.out.println(" null");  
  54. }else{  
  55. for(TableEvent event : list){  
  56. VariableBinding[] values = event.getColumns();  
  57. if(values == nullcontinue;  
  58. System.out.println("interface ---Index:"+values[0].getVariable().toString()+"  descr:"+getChinese(values[1].getVariable().toString())+"  type:"+values[2].getVariable().toString()+" speed:"+values[3].getVariable().toString()+" mac:"+getChinese(values[4].getVariable().toString())+" adminStatus:"+values[5].getVariable().toString()+"  operStatus:"+values[6].getVariable().toString());  
  59. }  
  60. }  
  61. //获取ip  
  62. OID[] ipcolumns = new OID[IP_OIDS.length];  
  63. for (int i = 0; i < IP_OIDS.length; i++)  
  64. ipcolumns[i] = new OID(IP_OIDS[i]);  
  65. @SuppressWarnings("unchecked")  
  66. List<TableEvent> iplist = tableUtils.getTable(target, ipcolumns, nullnull);  
  67. if(iplist.size()==1 && iplist.get(0).getColumns()==null){  
  68. System.out.println(" null");  
  69. }else{  
  70. for(TableEvent event : iplist){  
  71. VariableBinding[] values = event.getColumns();  
  72. if(values == nullcontinue;  
  73. System.out.println(" IP--->ipAdEntAddr:"+values[0].getVariable().toString()+"   ipAdEntIfIndex:"+values[1].getVariable().toString()+"   ipAdEntNetMask:"+values[2].getVariable().toString());  
  74. }  
  75. }  
  76. catch(Exception e){  
  77. e.printStackTrace();  
  78. }finally{  
  79. try {  
  80. if(transport!=null)  
  81. transport.close();  
  82. if(snmp!=null)  
  83. snmp.close();  
  84. catch (IOException e) {  
  85. e.printStackTrace();  
  86. }  
  87. }  
  88. }  


7、获取端口信息方法

[java]  view plain  copy
  1. //服务器端口集合  
  2. public static void collectPort() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] TCP_CONN = {"1.3.6.1.2.1.6.13.1.1"//status  
  7.         "1.3.6.1.2.1.6.13.1.3"}; //port  
  8.    
  9. String[] UDP_CONN = {"1.3.6.1.2.1.7.5.1.2"};  
  10. try {  
  11. transport = new DefaultUdpTransportMapping();  
  12. snmp = new Snmp(transport);  
  13. snmp.listen();  
  14. target = new CommunityTarget();  
  15. target.setCommunity(new OctetString("public"));  
  16. target.setRetries(2);  
  17. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  18. target.setTimeout(8000);  
  19. target.setVersion(SnmpConstants.version2c);  
  20. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  21. @Override  
  22. public PDU createPDU(Target arg0) {  
  23. PDU request = new PDU();  
  24. request.setType(PDU.GET);  
  25. return request;  
  26. }  
  27. });  
  28. //获取TCP 端口  
  29. OID[] columns = new OID[TCP_CONN.length];  
  30. for (int i = 0; i < TCP_CONN.length; i++)  
  31. columns[i] = new OID(TCP_CONN[i]);  
  32. @SuppressWarnings("unchecked")  
  33. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  34. if(list.size()==1 && list.get(0).getColumns()==null){  
  35. System.out.println(" null");  
  36. }else{  
  37. for(TableEvent event : list){  
  38. VariableBinding[] values = event.getColumns();  
  39. if(values == nullcontinue;  
  40. int status = Integer.parseInt(values[0].getVariable().toString());  
  41. System.out.println("status--->"+status+"   TCP_port--->"+values[1].getVariable().toString());  
  42. }  
  43. }  
  44. //获取udp 端口  
  45. OID[] udpcolumns = new OID[UDP_CONN.length];  
  46. for (int i = 0; i < UDP_CONN.length; i++)  
  47. udpcolumns[i] = new OID(UDP_CONN[i]);  
  48. @SuppressWarnings("unchecked")  
  49. List<TableEvent> udplist = tableUtils.getTable(target, udpcolumns, nullnull);  
  50. if(udplist.size()==1 && udplist.get(0).getColumns()==null){  
  51. System.out.println(" null");  
  52. }else{  
  53. for(TableEvent event : udplist){  
  54. VariableBinding[] values = event.getColumns();  
  55. if(values == nullcontinue;  
  56. String name = values[0].getVariable().toString();//name  
  57. System.out.println("UDP_port--->"+name);  
  58. }  
  59. }  
  60. catch(Exception e){  
  61. e.printStackTrace();  
  62. }finally{  
  63. try {  
  64. if(transport!=null)  
  65. transport.close();  
  66. if(snmp!=null)  
  67. snmp.close();  
  68. catch (IOException e) {  
  69. e.printStackTrace();  
  70. }  
  71. }  
  72. }  


8、获取安装的软件信息方法

[java]  view plain  copy
  1. //服务器安装软件集合  
  2. public static void collectSoft() {  
  3. TransportMapping transport = null ;  
  4. Snmp snmp = null ;  
  5. CommunityTarget target;  
  6. String[] oids =  
  7. {   "1.3.6.1.2.1.25.6.3.1.2",  //software  
  8.                     "1.3.6.1.2.1.25.6.3.1.4",  //type  
  9.     "1.3.6.1.2.1.25.6.3.1.5"}; //install date  
  10. try {  
  11. transport = new DefaultUdpTransportMapping();  
  12. snmp = new Snmp(transport);  
  13. snmp.listen();  
  14. target = new CommunityTarget();  
  15. target.setCommunity(new OctetString("public"));  
  16. target.setRetries(2);  
  17. target.setAddress(GenericAddress.parse("udp:127.0.0.1/161"));  
  18. target.setTimeout(8000);  
  19. target.setVersion(SnmpConstants.version2c);  
  20. TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {  
  21. @Override  
  22. public PDU createPDU(Target arg0) {  
  23. PDU request = new PDU();  
  24. request.setType(PDU.GET);  
  25. return request;  
  26. }  
  27. });  
  28. OID[] columns = new OID[oids.length];  
  29. for (int i = 0; i < oids.length; i++)  
  30. columns[i] = new OID(oids[i]);  
  31. @SuppressWarnings("unchecked")  
  32. List<TableEvent> list = tableUtils.getTable(target, columns, nullnull);  
  33. if(list.size()==1 && list.get(0).getColumns()==null){  
  34. System.out.println(" null");  
  35. }else{  
  36. for(TableEvent event : list){  
  37. VariableBinding[] values = event.getColumns();  
  38. if(values == nullcontinue;  
  39. String software = values[0].getVariable().toString();//software  
  40. String type = values[1].getVariable().toString();//type  
  41. String date = values[2].getVariable().toString();//date  
  42. System.out.println("软件名称--->"+getChinese(software)+"  type--->"+type+"  安装时间--->"+hexToDateTime(date.replace("'""")));  
  43. }  
  44. }  
  45. catch(Exception e){  
  46. e.printStackTrace();  
  47. }finally{  
  48. try {  
  49. if(transport!=null)  
  50. transport.close();  
  51. if(snmp!=null)  
  52. snmp.close();  
  53. catch (IOException e) {  
  54. e.printStackTrace();  
  55. }  
  56. }  
  57. }  


9、其他方法

[java]  view plain  copy
  1. /** 
  2.  * 获取磁盘的中文名字 
  3.  * 解决snmp4j中文乱码问题 
  4.  */  
  5. public static String getChinese(String octetString){  
  6. if(octetString == null || "".equals(octetString)   
  7.        || "null".equalsIgnoreCase(octetString)) return "";  
  8. try{  
  9. String[] temps = octetString.split(":");  
  10. if(temps.length < COLON_SIZE)  
  11. return octetString;  
  12. byte[] bs = new byte[temps.length];  
  13. for(int i=0;i<temps.length;i++)  
  14. bs[i] = (byte)Integer.parseInt(temps[i],16);  
  15.     return new String(bs,"GB2312");  
  16. }catch(Exception e){  
  17. return null;  
  18. }  
  19. }  
  20. /** 
  21.  * 将16进制的时间转换成标准的时间格式 
  22.  */  
  23. private static String hexToDateTime(String hexString) {  
  24. if(hexString == null || "".equals(hexString))  
  25. return "";  
  26. String dateTime = "";  
  27. try {  
  28. byte[] values = OctetString.fromHexString(hexString).getValue();  
  29. int year, month, day, hour, minute;  
  30.    
  31. year = values[0] * 256 + 256 + values[1];  
  32. month = values[2];  
  33. day = values[3];  
  34. hour = values[4];  
  35. minute = values[5];  
  36.    
  37. char format_str[] = new char[22];  
  38. int index = 3;  
  39. int temp = year;  
  40. for (; index >= 0; index--) {  
  41. format_str[index] = (char) (48 + (temp - temp / 10 * 10));  
  42. temp /= 10;  
  43. }  
  44. format_str[4] = '-';  
  45. index = 6;  
  46. temp = month;  
  47. for (; index >= 5; index--) {  
  48. format_str[index] = (char) (48 + (temp - temp / 10 * 10));  
  49. temp /= 10;  
  50. }  
  51. format_str[7] = '-';  
  52. index = 9;  
  53. temp = day;  
  54. for (; index >= 8; index--) {  
  55. format_str[index] = (char) (48 + (temp - temp / 10 * 10));  
  56. temp /= 10;  
  57. }  
  58. format_str[10] = ' ';  
  59. index = 12;  
  60. temp = hour;  
  61. for (; index >= 11; index--) {  
  62. format_str[index] = (char) (48 + (temp - temp / 10 * 10));  
  63. temp /= 10;  
  64. }  
  65. format_str[13] = ':';  
  66. index = 15;  
  67. temp = minute;  
  68. for (; index >= 14; index--) {  
  69. format_str[index] = (char) (48 + (temp - temp / 10 * 10));  
  70. temp /= 10;  
  71. }  
  72. dateTime = new String(format_str,0,format_str.length).substring(016);  
  73. catch (Exception e) {  
  74. //LogFactory.getLog(getClass()).error(e);  
  75. }  
  76. return dateTime;  
  77. }  

转载自https://blog.csdn.net/xumajie88/article/details/18406763

猜你喜欢

转载自blog.csdn.net/qq_33314107/article/details/80707045