SNMP4J文档中给的example不完整,在网上找了一天也没有找到一个好的例子,现在自己终于摸索出来了,就给大家做个参考吧。使用SNMP4JV2.0.2测试正常。
- /* 发送端使用net-snmp,命令如下:
- * snmptrap -e 0x0102030405 -v 3 -u myuser -a MD5 -A mypassword -l authNoPriv 218.195.60.1 42 .1.3.6.1.6.3.1.1.5.4 .1.3.6.1.2.1.2.2.1.1 i 7 .1.3.6.1.2.1.2.2.1.7 i 1 .1.3.6.1.2.1.2.2.1.8 i 1
- */
- public class TrapDeamon implements CommandResponder
- {
- private Snmp snmp;
- public void init() throws Exception
- {
- //create a threadpool to process the traps
- ThreadPool threadPool = ThreadPool.create("TrapDeamon", 3);
- MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
- String nsap = "udp:" + InetAddress.getLocalHost().getHostAddress() + "/162";
- Address listenAddress = GenericAddress.parse(System.getProperty("snmp4j.listenAddress", nsap));
- TransportMapping transport = null;
- // tcp or udp
- if (listenAddress instanceof UdpAddress)
- {
- transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress);
- }
- else
- {
- transport = new DefaultTcpTransportMapping((TcpAddress) listenAddress);
- }
- //construct a "snmp" instance to handle the snmp massage
- snmp = new Snmp(dispatcher, transport);
- //add msg handling module
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
- //add the enginID in the trap
- OctetString engineID = new OctetString(MPv3.createLocalEngineID());
- //create and add the userSecurityModel
- USM usm = new USM(SecurityProtocols.getInstance(),engineID, 0);
- SecurityModels.getInstance().addSecurityModel(usm);
- //add the securityProtocols,you can skip it if your users are noAuthNoPriv
- SecurityProtocols.getInstance().addDefaultProtocols();
- //create and add the user
- OctetString userName = new OctetString("myuser");
- OctetString password = new OctetString ("mypassword");
- UsmUser usmUser = new UsmUser(userName, AuthMD5.ID, password, null, null);
- snmp.getUSM().addUser(usmUser);
- //add other users here...
- snmp.listen();
- snmp.addCommandResponder(this);
- System.out.println("Listening..");
- }
- public void processPdu(CommandResponderEvent respEvnt)
- {
- String peerAddr = respEvnt.getPeerAddress().toString();
- try
- {
- String [] remoteAddr = peerAddr.split("/");
- String ip = remoteAddr[0];
- if (respEvnt != null && respEvnt.getPDU() != null)
- {
- PDU pdu = respEvnt.getPDU();
- switch (pdu.getType())
- {
- case -89://0xA7 represents V2,V3Trap
- parsePduV2(ip, pdu);
- break;
- case -92://0xA4 represents V1Trap
- parsePduV1(ip, pdu);
- break;
- default://not a Trap,ignore it
- break;
- }
- }
- }
- catch (Exception e)
- {
- System.out.println("Error occured in processPdu() of " + peerAddr);
- System.out.println(e.getMessage());
- e.printStackTrace();
- }
- }
- }