java利用snmp4j包来读取snmp协议数据(Manager端)

1 snmp简单介绍

java利用snmp4j包来读取snmp协议数据,很简单的一个流程,就是利用java来读取运行snmp协议的数据,例如服务器、PC机或者路由器等运行了snmp协议的设备。

snmp协议是什么呢?

简单网络管理协议(SNMP),由一组网络管理的标准组成,包含一个 应用层 协议(application layer protocol)、 数据库模型 (database schema)和一组资源对象。该协议能够支持 网络管理系统 ,用以监测连接到网络上的设备是否有任何引起管理上关注的情况。该协议是互联网工程工作小组(IETF,Internet Engineering TaskForce)定义的internet协议簇的一部分。SNMP的目标是管理 互联网 Internet上众多厂家生产的软硬件平台,因此SNMP受Internet标准 网络管理 框架的影响也很大。SNMP已经出到第三个版本的协议,其功能较以前已经大大地加强和改进了。

上面是百度百科上对于snmp的一个定义,其实很简单,就是用来管理网络、查看网络信息的一种协议。

2 在本机上开启snmp协议

那么如何在本机上开启snmp协议呢?

首先,在控制面板中找到“卸载程序”;

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

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

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

 

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

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

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

其中要注意的地方就是,在开启后,还要到服务里面给snmp协议添加public权限。

3 snmp4j.jar包的下载

包用的是snmp4j.jar,下载地址是:http://www.snmp4j.org

 

4 编码测试

 SnmpData:

 

 
  1. package com.test.snmp;

  2.  
  3. import java.io.IOException;

  4. import java.util.ArrayList;

  5. import java.util.List;

  6. import java.util.concurrent.CountDownLatch;

  7. import java.util.concurrent.TimeUnit;

  8.  
  9. import org.snmp4j.CommunityTarget;

  10. import org.snmp4j.PDU;

  11. import org.snmp4j.Snmp;

  12. import org.snmp4j.TransportMapping;

  13. import org.snmp4j.event.ResponseEvent;

  14. import org.snmp4j.event.ResponseListener;

  15. import org.snmp4j.mp.SnmpConstants;

  16. import org.snmp4j.smi.Address;

  17. import org.snmp4j.smi.GenericAddress;

  18. import org.snmp4j.smi.Integer32;

  19. import org.snmp4j.smi.Null;

  20. import org.snmp4j.smi.OID;

  21. import org.snmp4j.smi.OctetString;

  22. import org.snmp4j.smi.VariableBinding;

  23. import org.snmp4j.transport.DefaultUdpTransportMapping;

  24.  
  25. public class SnmpData {

  26.  
  27. public static final int DEFAULT_VERSION = SnmpConstants.version2c;

  28. public static final String DEFAULT_PROTOCOL = "udp";

  29. public static final int DEFAULT_PORT = 161;

  30. public static final long DEFAULT_TIMEOUT = 3 * 1000L;

  31. public static final int DEFAULT_RETRY = 3;

  32.  
  33. /**

  34. * 创建对象communityTarget,用于返回target

  35. *

  36. * @param targetAddress

  37. * @param community

  38. * @param version

  39. * @param timeOut

  40. * @param retry

  41. * @return CommunityTarget

  42. */

  43. public static CommunityTarget createDefault(String ip, String community) {

  44. Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip

  45. + "/" + DEFAULT_PORT);

  46. CommunityTarget target = new CommunityTarget();

  47. target.setCommunity(new OctetString(community));

  48. target.setAddress(address);

  49. target.setVersion(DEFAULT_VERSION);

  50. target.setTimeout(DEFAULT_TIMEOUT); // milliseconds

  51. target.setRetries(DEFAULT_RETRY);

  52. return target;

  53. }

  54. /*根据OID,获取单条消息*/

  55. public static void snmpGet(String ip, String community, String oid) {

  56.  
  57. CommunityTarget target = createDefault(ip, community);

  58. Snmp snmp = null;

  59. try {

  60. PDU pdu = new PDU();

  61. // pdu.add(new VariableBinding(new OID(new int[]

  62. // {1,3,6,1,2,1,1,2})));

  63. pdu.add(new VariableBinding(new OID(oid)));

  64.  
  65. DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();

  66. snmp = new Snmp(transport);

  67. snmp.listen();

  68. System.out.println("-------> 发送PDU <-------");

  69. pdu.setType(PDU.GET);

  70. ResponseEvent respEvent = snmp.send(pdu, target);

  71. System.out.println("PeerAddress:" + respEvent.getPeerAddress());

  72. PDU response = respEvent.getResponse();

  73.  
  74. if (response == null) {

  75. System.out.println("response is null, request time out");

  76. } else {

  77.  
  78. // Vector vbVect =

  79. // response.getVariableBindings();

  80. // System.out.println("vb size:" + vbVect.size());

  81. // if (vbVect.size() == 0) {

  82. // System.out.println("response vb size is 0 ");

  83. // } else {

  84. // VariableBinding vb = vbVect.firstElement();

  85. // System.out.println(vb.getOid() + " = " + vb.getVariable());

  86. // }

  87.  
  88. System.out.println("response pdu size is " + response.size());

  89. for (int i = 0; i < response.size(); i++) {

  90. VariableBinding vb = response.get(i);

  91. System.out.println(vb.getOid() + " = " + vb.getVariable());

  92. }

  93.  
  94. }

  95. System.out.println("SNMP GET one OID value finished !");

  96. } catch (Exception e) {

  97. e.printStackTrace();

  98. System.out.println("SNMP Get Exception:" + e);

  99. } finally {

  100. if (snmp != null) {

  101. try {

  102. snmp.close();

  103. } catch (IOException ex1) {

  104. snmp = null;

  105. }

  106. }

  107.  
  108. }

  109. }

  110. /*根据OID列表,一次获取多条OID数据,并且以List形式返回*/

  111. public static void snmpGetList(String ip, String community, List oidList)

  112. {

  113. CommunityTarget target = createDefault(ip, community);

  114. Snmp snmp = null;

  115. try {

  116. PDU pdu = new PDU();

  117.  
  118. for(String oid:oidList)

  119. {

  120. pdu.add(new VariableBinding(new OID(oid)));

  121. }

  122.  
  123. DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();

  124. snmp = new Snmp(transport);

  125. snmp.listen();

  126. System.out.println("-------> 发送PDU <-------");

  127. pdu.setType(PDU.GET);

  128. ResponseEvent respEvent = snmp.send(pdu, target);

  129. System.out.println("PeerAddress:" + respEvent.getPeerAddress());

  130. PDU response = respEvent.getResponse();

  131.  
  132. if (response == null) {

  133. System.out.println("response is null, request time out");

  134. } else {

  135.  
  136. System.out.println("response pdu size is " + response.size());

  137. for (int i = 0; i < response.size(); i++) {

  138. VariableBinding vb = response.get(i);

  139. System.out.println(vb.getOid() + " = " + vb.getVariable());

  140. }

  141.  
  142. }

  143. System.out.println("SNMP GET one OID value finished !");

  144. } catch (Exception e) {

  145. e.printStackTrace();

  146. System.out.println("SNMP Get Exception:" + e);

  147. } finally {

  148. if (snmp != null) {

  149. try {

  150. snmp.close();

  151. } catch (IOException ex1) {

  152. snmp = null;

  153. }

  154. }

  155.  
  156. }

  157. }

  158. /*根据OID列表,采用异步方式一次获取多条OID数据,并且以List形式返回*/

  159. public static void snmpAsynGetList(String ip, String community,List oidList)

  160. {

  161. CommunityTarget target = createDefault(ip, community);

  162. Snmp snmp = null;

  163. try {

  164. PDU pdu = new PDU();

  165.  
  166. for(String oid:oidList)

  167. {

  168. pdu.add(new VariableBinding(new OID(oid)));

  169. }

  170.  
  171. DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();

  172. snmp = new Snmp(transport);

  173. snmp.listen();

  174. System.out.println("-------> 发送PDU <-------");

  175. pdu.setType(PDU.GET);

  176. ResponseEvent respEvent = snmp.send(pdu, target);

  177. System.out.println("PeerAddress:" + respEvent.getPeerAddress());

  178. PDU response = respEvent.getResponse();

  179.  
  180. /*异步获取*/

  181. final CountDownLatch latch = new CountDownLatch(1);

  182. ResponseListener listener = new ResponseListener() {

  183. public void onResponse(ResponseEvent event) {

  184. ((Snmp) event.getSource()).cancel(event.getRequest(), this);

  185. PDU response = event.getResponse();

  186. PDU request = event.getRequest();

  187. System.out.println("[request]:" + request);

  188. if (response == null) {

  189. System.out.println("[ERROR]: response is null");

  190. } else if (response.getErrorStatus() != 0) {

  191. System.out.println("[ERROR]: response status"

  192. + response.getErrorStatus() + " Text:"

  193. + response.getErrorStatusText());

  194. } else {

  195. System.out.println("Received response Success!");

  196. for (int i = 0; i < response.size(); i++) {

  197. VariableBinding vb = response.get(i);

  198. System.out.println(vb.getOid() + " = "

  199. + vb.getVariable());

  200. }

  201. System.out.println("SNMP Asyn GetList OID finished. ");

  202. latch.countDown();

  203. }

  204. }

  205. };

  206.  
  207. pdu.setType(PDU.GET);

  208. snmp.send(pdu, target, null, listener);

  209. System.out.println("asyn send pdu wait for response...");

  210.  
  211. boolean wait = latch.await(30, TimeUnit.SECONDS);

  212. System.out.println("latch.await =:" + wait);

  213.  
  214. snmp.close();

  215.  
  216. System.out.println("SNMP GET one OID value finished !");

  217. } catch (Exception e) {

  218. e.printStackTrace();

  219. System.out.println("SNMP Get Exception:" + e);

  220. } finally {

  221. if (snmp != null) {

  222. try {

  223. snmp.close();

  224. } catch (IOException ex1) {

  225. snmp = null;

  226. }

  227. }

  228.  
  229. }

  230. }

  231. /*根据targetOID,获取树形数据*/

  232. public static void snmpWalk(String ip, String community, String targetOid)

  233. {

  234. CommunityTarget target = createDefault(ip, community);

  235. TransportMapping transport = null;

  236. Snmp snmp = null;

  237. try {

  238. transport = new DefaultUdpTransportMapping();

  239. snmp = new Snmp(transport);

  240. transport.listen();

  241.  
  242. PDU pdu = new PDU();

  243. OID targetOID = new OID(targetOid);

  244. pdu.add(new VariableBinding(targetOID));

  245.  
  246. boolean finished = false;

  247. System.out.println("----> demo start <----");

  248. while (!finished) {

  249. VariableBinding vb = null;

  250. ResponseEvent respEvent = snmp.getNext(pdu, target);

  251.  
  252. PDU response = respEvent.getResponse();

  253.  
  254. if (null == response) {

  255. System.out.println("responsePDU == null");

  256. finished = true;

  257. break;

  258. } else {

  259. vb = response.get(0);

  260. }

  261. // check finish

  262. finished = checkWalkFinished(targetOID, pdu, vb);

  263. if (!finished) {

  264. System.out.println("==== walk each vlaue :");

  265. System.out.println(vb.getOid() + " = " + vb.getVariable());

  266.  
  267. // Set up the variable binding for the next entry.

  268. pdu.setRequestID(new Integer32(0));

  269. pdu.set(0, vb);

  270. } else {

  271. System.out.println("SNMP walk OID has finished.");

  272. snmp.close();

  273. }

  274. }

  275. System.out.println("----> demo end <----");

  276. } catch (Exception e) {

  277. e.printStackTrace();

  278. System.out.println("SNMP walk Exception: " + e);

  279. } finally {

  280. if (snmp != null) {

  281. try {

  282. snmp.close();

  283. } catch (IOException ex1) {

  284. snmp = null;

  285. }

  286. }

  287. }

  288. }

  289.  
  290. private static boolean checkWalkFinished(OID targetOID, PDU pdu,

  291. VariableBinding vb) {

  292. boolean finished = false;

  293. if (pdu.getErrorStatus() != 0) {

  294. System.out.println("[true] responsePDU.getErrorStatus() != 0 ");

  295. System.out.println(pdu.getErrorStatusText());

  296. finished = true;

  297. } else if (vb.getOid() == null) {

  298. System.out.println("[true] vb.getOid() == null");

  299. finished = true;

  300. } else if (vb.getOid().size() < targetOID.size()) {

  301. System.out.println("[true] vb.getOid().size() < targetOID.size()");

  302. finished = true;

  303. } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {

  304. System.out.println("[true] targetOID.leftMostCompare() != 0");

  305. finished = true;

  306. } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {

  307. System.out

  308. .println("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");

  309. finished = true;

  310. } else if (vb.getOid().compareTo(targetOID) <= 0) {

  311. System.out.println("[true] Variable received is not "

  312. + "lexicographic successor of requested " + "one:");

  313. System.out.println(vb.toString() + " <= " + targetOID);

  314. finished = true;

  315. }

  316. return finished;

  317.  
  318. }

  319. /*根据targetOID,异步获取树形数据*/

  320. public static void snmpAsynWalk(String ip, String community, String oid)

  321. {

  322. final CommunityTarget target = createDefault(ip, community);

  323. Snmp snmp = null;

  324. try {

  325. System.out.println("----> demo start <----");

  326.  
  327. DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();

  328. snmp = new Snmp(transport);

  329. snmp.listen();

  330.  
  331. final PDU pdu = new PDU();

  332. final OID targetOID = new OID(oid);

  333. final CountDownLatch latch = new CountDownLatch(1);

  334. pdu.add(new VariableBinding(targetOID));

  335.  
  336. ResponseListener listener = new ResponseListener() {

  337. public void onResponse(ResponseEvent event) {

  338. ((Snmp) event.getSource()).cancel(event.getRequest(), this);

  339.  
  340. try {

  341. PDU response = event.getResponse();

  342. // PDU request = event.getRequest();

  343. // System.out.println("[request]:" + request);

  344. if (response == null) {

  345. System.out.println("[ERROR]: response is null");

  346. } else if (response.getErrorStatus() != 0) {

  347. System.out.println("[ERROR]: response status"

  348. + response.getErrorStatus() + " Text:"

  349. + response.getErrorStatusText());

  350. } else {

  351. System.out

  352. .println("Received Walk response value :");

  353. VariableBinding vb = response.get(0);

  354.  
  355. boolean finished = checkWalkFinished(targetOID,

  356. pdu, vb);

  357. if (!finished) {

  358. System.out.println(vb.getOid() + " = "

  359. + vb.getVariable());

  360. pdu.setRequestID(new Integer32(0));

  361. pdu.set(0, vb);

  362. ((Snmp) event.getSource()).getNext(pdu, target,

  363. null, this);

  364. } else {

  365. System.out

  366. .println("SNMP Asyn walk OID value success !");

  367. latch.countDown();

  368. }

  369. }

  370. } catch (Exception e) {

  371. e.printStackTrace();

  372. latch.countDown();

  373. }

  374.  
  375. }

  376. };

  377.  
  378. snmp.getNext(pdu, target, null, listener);

  379. System.out.println("pdu 已发送,等到异步处理结果...");

  380.  
  381. boolean wait = latch.await(30, TimeUnit.SECONDS);

  382. System.out.println("latch.await =:" + wait);

  383. snmp.close();

  384.  
  385. System.out.println("----> demo end <----");

  386. } catch (Exception e) {

  387. e.printStackTrace();

  388. System.out.println("SNMP Asyn Walk Exception:" + e);

  389. }

  390. }

  391. /*根据OID和指定string来设置设备的数据*/

  392. public static void setPDU(String ip,String community,String oid,String val) throws IOException

  393. {

  394. CommunityTarget target = createDefault(ip, community);

  395. Snmp snmp = null;

  396. PDU pdu = new PDU();

  397. pdu.add(new VariableBinding(new OID(oid),new OctetString(val)));

  398. pdu.setType(PDU.SET);

  399.  
  400. DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();

  401. snmp = new Snmp(transport);

  402. snmp.listen();

  403. System.out.println("-------> 发送PDU <-------");

  404. snmp.send(pdu, target);

  405. snmp.close();

  406. }

  407. }

 

SnmpTest:

 

 
  1. package com.test.snmp;

  2.  
  3. import java.util.ArrayList;

  4. import java.util.List;

  5. import org.snmp4j.log.ConsoleLogFactory;

  6. import org.snmp4j.log.LogAdapter;

  7. import org.snmp4j.log.LogFactory;

  8. import com.test.snmp.SnmpData;

  9.  
  10. public class SnmpTest {

  11.  
  12. /**

  13. * @param args

  14. */

  15. public static void main(String[] args) {

  16.  
  17. // TODO Auto-generated method stub

  18. SnmpTest test = new SnmpTest();

  19.  
  20. test.testGet();

  21.  
  22. }

  23.  
  24. public void testGet()

  25. {

  26. String ip = "127.0.0.1";

  27. String community = "public";

  28. String oidval = "1.3.6.1.2.1.1.6.0";

  29. SnmpData.snmpGet(ip, community, oidval);

  30. }

  31.  
  32.  
  33. public void testGetList(){

  34. String ip = "127.0.0.1";

  35.      String community = "public";

  36.      List oidList=new ArrayList();

  37.      oidList.add("1.3.6.1.2.1.1.5.0");

  38.      oidList.add("1.3.6.1.2.1.1.7.0");

  39.    SnmpData.snmpGetList(ip, community, oidList);

  40. }

  41.  
  42.  
  43. public void testGetAsyList()

  44. {

  45. String ip = "127.0.0.1";

  46. String community = "public";

  47. List oidList=new ArrayList();

  48. oidList.add("1.3.6.1.2.1");

  49. oidList.add("1.3.6.1.2.12");

  50. SnmpData.snmpAsynGetList(ip, community, oidList);

  51. System.out.println("i am first!");

  52. }

  53.  
  54.  
  55. public void testWalk()

  56. {

  57. String ip = "127.0.0.1";

  58. String community = "public";

  59. String targetOid = "1.3.6.1.2.1.1.5.0";

  60. SnmpData.snmpWalk(ip, community, targetOid);

  61. }

  62.  
  63.  
  64. public void testAsyWalk()

  65. {

  66. String ip = "127.0.0.1";

  67. String community = "public";

  68. // 异步采集数据

  69. SnmpData.snmpAsynWalk(ip, community, "1.3.6.1.2.1.25.4.2.1.2");

  70. }

  71.  
  72.  
  73. public void testSetPDU() throws Exception

  74. {

  75. String ip = "127.0.0.1";

  76. String community = "public";

  77. SnmpData.setPDU(ip, community, "1.3.6.1.2.1.1.6.0","jianghuiwen");

  78. }

  79.  
  80.  
  81. public void testVersion()

  82. {

  83. System.out.println(org.snmp4j.version.VersionInfo.getVersion());

  84. }

  85. }

文档和源码csdn下载:http://download.csdn.net/detail/davebobo/9509435

ref: http://www.tuicool.com/articles/FF7fEbi

ref: http://blog.chinaunix.net/uid-21857285-id-3340206.html

-------------------------更新--------------------------------------

Trap功能的实现:

下面是两个用于发送和接收Trap报文信息的类:

接收Trap消息类:

 

 
  1. import java.io.IOException;

  2. import java.net.UnknownHostException;

  3. import java.util.Vector;

  4.  
  5. import org.snmp4j.CommandResponder;

  6. import org.snmp4j.CommandResponderEvent;

  7. import org.snmp4j.MessageDispatcherImpl;

  8. import org.snmp4j.Snmp;

  9. import org.snmp4j.TransportMapping;

  10. import org.snmp4j.mp.MPv1;

  11. import org.snmp4j.mp.MPv2c;

  12. import org.snmp4j.mp.MPv3;

  13. import org.snmp4j.security.SecurityModels;

  14. import org.snmp4j.security.SecurityProtocols;

  15. import org.snmp4j.security.USM;

  16. import org.snmp4j.smi.Address;

  17. import org.snmp4j.smi.GenericAddress;

  18. import org.snmp4j.smi.OctetString;

  19. import org.snmp4j.smi.TcpAddress;

  20. import org.snmp4j.smi.UdpAddress;

  21. import org.snmp4j.smi.VariableBinding;

  22. import org.snmp4j.transport.DefaultTcpTransportMapping;

  23. import org.snmp4j.transport.DefaultUdpTransportMapping;

  24. import org.snmp4j.util.MultiThreadedMessageDispatcher;

  25. import org.snmp4j.util.ThreadPool;

  26.  
  27. /**

  28. * 本类用于监听代理进程的Trap信息

  29. *

  30. * @author zhanjia

  31. *

  32. */

  33. public class MultiThreadedTrapReceiver implements CommandResponder {

  34.  
  35. private MultiThreadedMessageDispatcher dispatcher;

  36. private Snmp snmp = null;

  37. private Address listenAddress;

  38. private ThreadPool threadPool;

  39.  
  40. public MultiThreadedTrapReceiver() {

  41. // BasicConfigurator.configure();

  42. }

  43.  
  44. private void init() throws UnknownHostException, IOException {

  45. threadPool = ThreadPool.create("Trap", 2);

  46. dispatcher = new MultiThreadedMessageDispatcher(threadPool,

  47. new MessageDispatcherImpl());

  48. listenAddress = GenericAddress.parse(System.getProperty(

  49. "snmp4j.listenAddress", "udp:192.168.1.23/162")); // 本地IP与监听端口

  50. TransportMapping transport;

  51. // 对TCP与UDP协议进行处理

  52. if (listenAddress instanceof UdpAddress) {

  53. transport = new DefaultUdpTransportMapping(

  54. (UdpAddress) listenAddress);

  55. } else {

  56. transport = new DefaultTcpTransportMapping(

  57. (TcpAddress) listenAddress);

  58. }

  59. snmp = new Snmp(dispatcher, transport);

  60. snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());

  61. snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());

  62. snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());

  63. USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3

  64. .createLocalEngineID()), 0);

  65. SecurityModels.getInstance().addSecurityModel(usm);

  66. snmp.listen();

  67. }

  68.  
  69.  
  70. public void run() {

  71. try {

  72. init();

  73. snmp.addCommandResponder(this);

  74. System.out.println("开始监听Trap信息!");

  75. } catch (Exception ex) {

  76. ex.printStackTrace();

  77. }

  78. }

  79.  
  80. /**

  81. * 实现CommandResponder的processPdu方法, 用于处理传入的请求、PDU等信息

  82. * 当接收到trap时,会自动进入这个方法

  83. *

  84. * @param respEvnt

  85. */

  86. public void processPdu(CommandResponderEvent respEvnt) {

  87. // 解析Response

  88. if (respEvnt != null && respEvnt.getPDU() != null) {

  89. Vector recVBs = respEvnt.getPDU().getVariableBindings();

  90. for (int i = 0; i < recVBs.size(); i++) {

  91. VariableBinding recVB = recVBs.elementAt(i);

  92. System.out.println(recVB.getOid() + " : " + recVB.getVariable());

  93. }

  94. }

  95. }

  96.  
  97. public static void main(String[] args) {

  98. MultiThreadedTrapReceiver multithreadedtrapreceiver = new MultiThreadedTrapReceiver();

  99. multithreadedtrapreceiver.run();

  100. }

  101.  
  102. }

发送Trap消息的类:

 

 

 
  1. import java.io.IOException;

  2. import java.util.Vector;

  3.  
  4. import org.snmp4j.CommunityTarget;

  5. import org.snmp4j.PDU;

  6. import org.snmp4j.Snmp;

  7. import org.snmp4j.TransportMapping;

  8. import org.snmp4j.event.ResponseEvent;

  9. import org.snmp4j.mp.SnmpConstants;

  10. import org.snmp4j.smi.Address;

  11. import org.snmp4j.smi.GenericAddress;

  12. import org.snmp4j.smi.OID;

  13. import org.snmp4j.smi.OctetString;

  14. import org.snmp4j.smi.VariableBinding;

  15. import org.snmp4j.transport.DefaultUdpTransportMapping;

  16.  
  17. /**

  18. * 本类用于向管理进程发送Trap信息

  19. *

  20. * @author zhanjia

  21. *

  22. */

  23. public class SnmpUtilSendTrap {

  24.  
  25. private Snmp snmp = null;

  26.  
  27. private Address targetAddress = null;

  28.  
  29. public void initComm() throws IOException {

  30.  
  31. // 设置管理进程的IP和端口

  32. targetAddress = GenericAddress.parse("udp:192.168.1.23/162");

  33. TransportMapping transport = new DefaultUdpTransportMapping();

  34. snmp = new Snmp(transport);

  35. transport.listen();

  36.  
  37. }

  38.  
  39. /**

  40. * 向管理进程发送Trap报文

  41. *

  42. * @throws IOException

  43. */

  44. public void sendPDU() throws IOException {

  45.  
  46. // 设置 target

  47. CommunityTarget target = new CommunityTarget();

  48. target.setAddress(targetAddress);

  49.  
  50. // 通信不成功时的重试次数

  51. target.setRetries(2);

  52. // 超时时间

  53. target.setTimeout(1500);

  54. // snmp版本

  55. target.setVersion(SnmpConstants.version2c);

  56.  
  57. // 创建 PDU

  58. PDU pdu = new PDU();

  59. pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),

  60. new OctetString("SnmpTrap")));

  61. pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"),

  62. new OctetString("JavaEE")));

  63. pdu.setType(PDU.TRAP);

  64.  
  65. // 向Agent发送PDU,并接收Response

  66. ResponseEvent respEvnt = snmp.send(pdu, target);

  67.  
  68. // 解析Response

  69. if (respEvnt != null && respEvnt.getResponse() != null) {

  70. Vector recVBs = respEvnt.getResponse()

  71. .getVariableBindings();

  72. for (int i = 0; i < recVBs.size(); i++) {

  73. VariableBinding recVB = recVBs.elementAt(i);

  74. System.out.println(recVB.getOid() + " : " + recVB.getVariable());

  75. }

  76. }

  77. }

  78.  
  79. public static void main(String[] args) {

  80. try {

  81. SnmpUtilSendTrap util = new SnmpUtilSendTrap();

  82. util.initComm();

  83. util.sendPDU();

  84. } catch (IOException e) {

  85. e.printStackTrace();

  86. }

  87. }

  88.  
  89. }

 

1、运行MultiThreadedTrapReceiver类,提示“开始监听Trap信息!”并处理监听状态

2、运行SnmpUtilSendTrap类,运行完毕后,将会在“开始监听Trap信息!”后面显示:

1.3.6.1.2.3377.10.1.1.1.1 : SnmpTrap
1.3.6.1.2.3377.10.1.1.1.2 : JavaEE

MultiThreadedTrapReceiver输出面板中显示以上两行即表示测试成功!

说明:

      本例只在本人电脑上测试过,操作系统为Windows

ref:http://www.iteye.com/topic/308836
-----------------------------------------------------更新20160621-------------------------------------------------

接下来问题又来了,我们发的trap消息如果manager掉线我们应该考虑将trap消息保存下来,此时snmp inform就用上场了。详解请看下文:http://blog.csdn.net/davebobo/article/details/51730688

你可能感兴趣的:(JAVA)