SNMP4j实现同步和异步的Walk的示例micmiu

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SNMP4j实现同步和异步的Walk的示例micmiu 目录:
•环境参数
•代码示例
o同步WALK
o异步WALK
[一]、环境参数
•jdk 1.6.0_18
•snmp4j 1.11.3
[二]、代码示例
1.同步WALK(v2c)
代码:SnmpWalk.java
1 package com.micmiu.snmp4j.demo1x;
2
3 import java.io.IOException;
4
5 import munityTarget;
6 import org.snmp4j.PDU;
7 import org.snmp4j.Snmp;
8 import org.snmp4j.TransportMapping;
9 import org.snmp4j.event.ResponseEvent;
10 import org.snmp4j.mp.SnmpConstants;
11 import org.snmp4j.smi.Address;
12 import org.snmp4j.smi.GenericAddress;
13 import org.snmp4j.smi.Integer32;
14 import org.snmp4j.smi.Null;
15 import org.snmp4j.smi.OID;
16 import org.snmp4j.smi.OctetString;
17 import org.snmp4j.smi.VariableBinding;
18 import org.snmp4j.transport.DefaultUdpTransportMapping;
19
20 /**
21 * 演示:WALK的方式获取值
22 *
23 * blog
24 *
25 * @author Michael
26 */
27 public class SnmpWalk {
28
29 public static final int DEFAULT_VERSION =
SnmpConstants.version2c;
30 public static final String DEFAULT_PROTOCOL = "udp";
31 public static final int DEFAULT_PORT = 161;
32 public static final long DEFAULT_TIMEOUT = 3 * 1000L;
33 public static final int DEFAULT_RETRY = 3;
34
35 /**
36 * 创建对象communityTarget
37 *
38 * @param targetAddress
39 * @param community
40 * @param version
41 * @param timeOut
42 * @param retry
43 * @return CommunityTarget
44 */
45 public static CommunityTarget createDefault(String ip,
String community) {
46 Address address =
GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
47 + "/" + DEFAULT_PORT);
48 CommunityTarget target = new CommunityTarget();
49 target.setCommunity(new OctetString(community));
50 target.setAddress(address);
51 target.setVersion(DEFAULT_VERSION);
52 target.setTimeout(DEFAULT_TIMEOUT); //
milliseconds
53 target.setRetries(DEFAULT_RETRY);
54 return target;
55 }
56
57 /**
58 * @param ip
59 * @param community
60 * @param oid
61 */
62 public static void snmpWalk(String ip, String community,
String targetOid) { 63
64 CommunityTarget target =
SnmpUtil.createDefault(ip, community);
65 TransportMapping transport = null;
66 Snmp snmp = null;
67 try {
68 transport = new
DefaultUdpTransportMapping();
69 snmp = new Snmp(transport);
70 transport.listen();
71
72 PDU pdu = new PDU();
73 OID targetOID = new OID(targetOid);
74 pdu.add(new VariableBinding(targetOID));
75
76 boolean finished = false;
77 System.out.println("----> demo start <----
");
78 while (!finished) {
79 VariableBinding vb = null;
80 ResponseEvent respEvent =
snmp.getNext(pdu, target);
81
82 PDU response =
respEvent.getResponse();
83
84 if (null == response) {
8 5
System.out.println("respon sePDU == null");
86 finished = true;
87 break;
88 } else {
89 vb = response.get(0);
90 }
91 // check finish
92 finished =
checkWalkFinished(targetOID, pdu, vb);
93 if (!finished) {
94 System.out.println("====
walk each vlaue :");
9 5
System.out.println(vb.getO id() + " = " + vb.getVariable());
96
97 // Set up the variable
binding for the next entry.
98 pdu.setRequestID(new
Integer32(0));
99 pdu.set(0, vb); 100 } else {
101 System.out.println("SNMP
walk OID has finished.");
102 snmp.close(); 103 }
104 }
105 System.out.println("----> demo end <----
");
106 } catch (Exception e) {
107 e.printStackTrace();
108 System.out.println("SNMP walk Exception:
" + e);
109 } finally {
110 if (snmp != null) {
111 try {
112 snmp.close();
113 } catch (IOException ex1) { 114 snmp = null;
115 }
116 }
117 }
118
119 }
120
121 /**
122 * 1)responsePDU == null<br>
123 * 2)responsePDU.getErrorStatus() != 0<br>
124 * 3)responsePDU.get(0).getOid() == null<br>
125 * 4)responsePDU.get(0).getOid().size() <
targetOID.size()<br>
12 6
*
5)targetOID.leftMostCompare(targetOID.size(),responsePDU.get(0).g etOid())
127 * !=0<br>
12 8
*
6)Null.isExceptionSyntax(responsePDU.get(0).getVariable().getSynt ax())<br>
129 * 7)responsePDU.get(0).getOid().compareTo(targetOID) <=
0<br>
130 *
131 * @param resquestPDU 132 * @param targetOID 133 * @param responsePDU 134 * @param vb
135 * @return
136 */
137 private static boolean checkWalkFinished(OID targetOID,
PDU pdu,
138 VariableBinding vb) { 139 boolean finished = false;
140 if (pdu.getErrorStatus() != 0) {
141 System.out.println("[true]
responsePDU.getErrorStatus() != 0 ");
14 2
System.out.println(pdu.getErrorStatusText ());
143 finished = true;
144 } else if (vb.getOid() == null) {
145 System.out.println("[true] vb.getOid() ==
null");
146 finished = true;
147 } else if (vb.getOid().size() < targetOID.size())
{
148 System.out.println("[true]
vb.getOid().size() < targetOID.size()"); 149 finished = true;
150 } else if
(targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
151 System.out.println("[true]
targetOID.leftMostCompare() != 0");
152 finished = true;
153 } else if
(Null.isExceptionSyntax(vb.getVariable().getSyntax())) { 154 System.out
155 .println("[true]
Null.isExceptionSyntax(vb.getVariable().getSyntax())"); 156 finished = true;
157 } else if (vb.getOid().compareTo(targetOID) <= 0)
{
158 System.out.println("[true] Variable
received is not "
159 + "lexicographic
successor of requested " + "one:");
160 System.out.println(vb.toString() + " <= "
+ targetOID);
161 finished = true;
162 }
163 return finished;
164
165 }
166
167 /**
168 *
169 * @param args
170 */
171 public static void main(String[] args) {
172 String ip = "192.168.8.254";
173 String community = "public";
174 // 1.3.6.1.2.1.2.2.1.2
175 String targetOid = ".1.3.6.1.2.1.1";
176 SnmpWalk.snmpWalk(ip, community, targetOid);
177
178 }
179
180 }
运行结果:
----> demo start <----
==== walk each vlaue :
1.3.6.1.
2.1.1.1.0 = H3C ICG2000
H3C Comware Platform Software
Comware Software Version 5.20, Release 2104P02
Copyright(c) 2004-2010 Hangzhou H3C Technologies Co., Ltd.
==== walk each vlaue :
1.3.6.1.
2.1.1.2.0 = 1.
3.6.1.
4.1.25506.1.287
==== walk each vlaue :
1.3.6.1.
2.1.1.
3.0 = 39 days, 21:47:28.41
==== walk each vlaue :
1.3.6.1.
2.1.1.4.0 = R&D Hangzhou, Hangzhou H3C Technologies Co., Ltd.
==== walk each vlaue :
1.3.6.1.
2.1.1.5.0 = HX_ICG2000
==== walk each vlaue :
1.3.6.1.
2.1.1.6.0 = Hangzhou, China
==== walk each vlaue :
1.3.6.1.
2.1.1.7.0 = 78
[true] targetOID.leftMostCompare() != 0
SNMP walk OID has finished.
----> demo end <----
2.异步WALK(v2c)
代码:SnmpWalkAsyn.java
1 package com.micmiu.snmp4j.demo1x;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.concurrent.CountDownLatch;
6 import java.util.concurrent.TimeUnit;
7
8 import munityTarget;
9 import org.snmp4j.PDU;
10 import org.snmp4j.Snmp;
11 import org.snmp4j.event.ResponseEvent;
12 import org.snmp4j.event.ResponseListener;
13 import org.snmp4j.mp.SnmpConstants;
14 import org.snmp4j.smi.Address;
15 import org.snmp4j.smi.GenericAddress;
16 import org.snmp4j.smi.Integer32;
17 import org.snmp4j.smi.Null;
18 import org.snmp4j.smi.OID;
19 import org.snmp4j.smi.OctetString;
20 import org.snmp4j.smi.VariableBinding;
21 import org.snmp4j.transport.DefaultUdpTransportMapping;
22
23 /**
24 * 演示:异步GET OID值
25 *
26 * blog
27 *
28 * @author Michael
29 *
30 */
31 public class SnmpWalkAsyn {
32
33 public static final int DEFAULT_VERSION =
SnmpConstants.version2c;
34 public static final String DEFAULT_PROTOCOL = "udp";
35 public static final int DEFAULT_PORT = 161;
36 public static final long DEFAULT_TIMEOUT = 3 * 1000L;
37 public static final int DEFAULT_RETRY = 3;
38
39 /**
40 * 创建对象communityTarget
41 *
42 * @param targetAddress
43 * @param community
44 * @param version
45 * @param timeOut
46 * @param retry
47 * @return CommunityTarget
48 */
49 public static CommunityTarget createDefault(String ip,
String community) {
50 Address address =
GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
51 + "/" + DEFAULT_PORT);
52 CommunityTarget target = new CommunityTarget();
53 target.setCommunity(new OctetString(community));
54 target.setAddress(address);
55 target.setVersion(DEFAULT_VERSION);
56 target.setTimeout(DEFAULT_TIMEOUT); //
milliseconds
57 target.setRetries(DEFAULT_RETRY);
58 return target;
59 }
60
61 /**
62 * 异步采集信息
63 *
64 * @param ip
65 * @param community
66 * @param oid
67 */
68 public static void snmpAsynWalk(String ip, String
community, String oid) {
69 final CommunityTarget target = createDefault(ip,
community);
70 Snmp snmp = null;
71 try {
72 System.out.println("----> demo start <----
");
73
74 DefaultUdpTransportMapping transport = new
DefaultUdpTransportMapping();
75 snmp = new Snmp(transport);
76 snmp.listen();
77
78 final PDU pdu = new PDU();
79 final OID targetOID = new OID(oid);
80 final CountDownLatch latch = new
CountDownLatch(1);
81 pdu.add(new VariableBinding(targetOID));
82
83 ResponseListener listener = new
ResponseListener() {
84 public void
onResponse(ResponseEvent event) {
85 ((Snmp)
event.getSource()).cancel(event.getRequest(), this);
86
87 try {
88 PDU response =
event.getResponse();
89 // PDU request =
event.getRequest();
90 //
System.out.println("[request]:" + request);
91 if (response ==
null) {
9 2
System.out .println("[ERROR]: response is null");
93 } else if
(response.getErrorStatus() != 0) {
9 4
System.out .println("[ERROR]: response status"
9
5 + response.getErrorStatus() + " Text:"
9
6 + response.getErrorStatusText());
97 } else {
98 System.ou
t
9
9 .println("Received Walk response value :");
10 0
VariableB inding vb = response.get(0);
101
102 boolean
finished = checkWalkFinished(targetOID,
10
3 pdu, vb);
104 if
(!finished) {
10 5
S ystem.out.println(vb.getOid() + " = "
10
6 + vb.getVariable());
10 7
p du.setRequestID(new Integer32(0));
10 8
p du.set(0, vb);
10 9
( (Snmp) event.getSource()).getNext(pdu, target,
11
0 null, this);
111 } else {
11 2
S ystem.out
11
3 .println("SNMP Asyn walk OID value success !");
11 4
l atch.countDown();
115 }
116 }
117 } catch (Exception e) {
11 8
e.printStackTrace ();
11 9
latch.countDown() ;
120 } 121
122 }
123 };
124
125 snmp.getNext(pdu, target, null,
listener);
126 System.out.println("pdu 已发送,等到异步处
理结果..."); 127
128 boolean wait = latch.await(30,
TimeUnit.SECONDS);
129 System.out.println("latch.await =:" +
wait);
130 snmp.close(); 131
132 System.out.println("----> demo end <----
");
133 } catch (Exception e) {
134 e.printStackTrace();
135 System.out.println("SNMP Asyn Walk
Exception:" + e); 136 } 137
138 }
139
140 private static boolean checkWalkFinished(OID walkOID, PDU
pdu,
141 VariableBinding vb) { 142 boolean finished = false;
143 if (pdu.getErrorStatus() != 0) {
144 System.out.println("[true]
pdu.getErrorStatus() != 0 ");
14 5
System.out.println(pdu.getErrorStatusText ());
146 finished = true;
147 } else if (vb.getOid() == null) {
148 System.out.println("[true] vb.getOid() ==
null");
149 finished = true;
150 } else if (vb.getOid().size() < walkOID.size()) {
151 System.out.println("[true]
vb.getOid().size() < targetOID.size()"); 152 finished = true;
153 } else if
(walkOID.leftMostCompare(walkOID.size(), vb.getOid()) != 0) {
154 System.out.println("[true]
targetOID.leftMostCompare() != 0");
155 finished = true;
156 } else if
(Null.isExceptionSyntax(vb.getVariable().getSyntax())) { 157 System.out
158 .println("[true]
Null.isExceptionSyntax(vb.getVariable().getSyntax())");
159 finished = true;
160 } else if (vb.getOid().compareTo(walkOID) <= 0) {
161 System.out.println("[true]
vb.getOid().compareTo(walkOID) <= 0 ");
162 finished = true;
163 }
164 return finished;
165
166 }
167
168 /**
169 *
170 * @param args
171 */
172 public static void main(String[] args) {
173
174 String ip = "192.168.8.254";
175 String community = "public";
176
177 List<String> oidList = new ArrayList<String>(); 178 oidList.add(".1.3.6.1.2.1.1.1.0");
179 oidList.add(".1.3.6.1.2.1.1.3.0");
180 oidList.add(".1.3.6.1.2.1.1.5.0");
181 // 异步采集数据
182 SnmpWalkAsyn.snmpAsynWalk(ip, community,
"1.3.6.1.2.1.1");
183
184 }
185 }
运行结果:
----> demo start <----
pdu 已发送,等到异步处理结果...
Received Walk response value :
1.3.6.1.
2.1.1.1.0 = H3C ICG2000
H3C Comware Platform Software
Comware Software Version 5.20, Release 2104P02
Copyright(c) 2004-2010 Hangzhou H3C Technologies Co., Ltd.
Received Walk response value :
1.3.6.1.
2.1.1.2.0 = 1.
3.6.1.
4.1.25506.1.287
Received Walk response value :
1.3.6.1.
2.1.1.
3.0 = 39 days, 21:52:48.80
Received Walk response value :
1.3.6.1.
2.1.1.4.0 = R&D Hangzhou, Hangzhou H3C Technologies Co., Ltd.
Received Walk response value :
1.3.6.1.
2.1.1.5.0 = HX_ICG2000
Received Walk response value :
1.3.6.1.
2.1.1.6.0 = Hangzhou, China
Received Walk response value :
1.3.6.1.
2.1.1.7.0 = 78
Received Walk response value :
[true] targetOID.leftMostCompare() != 0
SNMP Asyn walk OID value success !
latch.await =:true
----> demo end <----。

相关文档
最新文档