码迷,mamicode.com
首页 > 其他好文 > 详细

SNMP4j实现Trap的示例

时间:2015-05-20 16:32:46      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

目录:

  • 环境参数
  • 代码示例

[一]、环境参数

  • jdk 1.6.0_18
  • snmp4j 1.11.3

[二]、代码示例

1. Trap接收器的实现

代码:SnmpTrapMultiThreadReceiver.java

package com.micmiu.snmp4j.demo1x;
 
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Vector;
 
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;
 
/**
 * 演示SNMP Trap多线程接收解析信息
 *
 * @blog http://www.micmiu.com
 * @author Michael
 */
public class SnmpTrapMultiThreadReceiver implements CommandResponder {
	private MultiThreadedMessageDispatcher dispatcher;
	private Snmp snmp = null;
	private Address listenAddress;
	private ThreadPool threadPool;
 
	public SnmpTrapMultiThreadReceiver() {
	}
 
	private void init() throws UnknownHostException, IOException {
		threadPool = ThreadPool.create("TrapPool", 2);
		dispatcher = new MultiThreadedMessageDispatcher(threadPool,
				new MessageDispatcherImpl());
		listenAddress = GenericAddress.parse(System.getProperty(
				"snmp4j.listenAddress", "udp:127.0.0.1/162"));
		TransportMapping transport;
		if (listenAddress instanceof UdpAddress) {
			transport = new DefaultUdpTransportMapping(
					(UdpAddress) listenAddress);
		} else {
			transport = new DefaultTcpTransportMapping(
					(TcpAddress) listenAddress);
		}
		snmp = new Snmp(dispatcher, transport);
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
		USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
				MPv3.createLocalEngineID()), 0);
		SecurityModels.getInstance().addSecurityModel(usm);
		snmp.listen();
	}
 
	public void run() {
		System.out.println("----> Trap Receiver run ... <----");
		try {
			init();
			snmp.addCommandResponder(this);
			System.out.println("----> 开始监听端口,等待Trap message  <----");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
 
	@SuppressWarnings("unchecked")
	public void processPdu(CommandResponderEvent event) {
		System.out.println("----> 开始解析ResponderEvent: <----");
		if (event == null || event.getPDU() == null) {
			System.out.println("[Warn] ResponderEvent or PDU is null");
			return;
		}
		Vector<VariableBinding> vbVect = event.getPDU().getVariableBindings();
		for (VariableBinding vb : vbVect) {
			System.out.println(vb.getOid() + " = " + vb.getVariable());
		}
		System.out.println("---->  本次ResponderEvent 解析结束 <----");
	}
 
	public static void main(String[] args) {
		SnmpTrapMultiThreadReceiver trapReceiver = new SnmpTrapMultiThreadReceiver();
		trapReceiver.run();
	}
}

运行结果:

----> Trap Receiver run ... <----
----> 开始监听端口,等待Trap message  <----



2. Trap 发送消息的模拟实现

代码:SnmpTrapSendDemo.java

package com.micmiu.snmp4j.demo1x;
 
import java.io.IOException;
 
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TimeTicks;
import org.snmp4j.smi.UnsignedInteger32;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
 
/**
 * 模拟Trap发送消息
 * @blog http://www.micmiu.com
 * @author Michael
 */
public class SnmpTrapSendDemo {
 
	public static final int DEFAULT_VERSION = SnmpConstants.version2c;
	public static final long DEFAULT_TIMEOUT = 3 * 1000L;
	public static final int DEFAULT_RETRY = 3;
 
	private Snmp snmp = null;
	private CommunityTarget target = null;
 
	public void init() throws IOException {
		System.out.println("----> 初始 Trap 的IP和端口 <----");
		target = createTarget4Trap("udp:127.0.0.1/162");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();
	}
 
	/**
	 * 向接收器发送Trap 信息
	 *
	 * @throws IOException
	 */
	public void sendPDU() throws IOException {
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(
				new OID(".1.3.6.1.2.1.1.1.0"),
				new OctetString("SNMP Trap Test.see more:http://www.micmiu.com")));
		pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(
				new UnsignedInteger32(System.currentTimeMillis() / 1000)
						.getValue())));
		pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(
				".1.3.6.1.6.3.1.1.4.3")));
 
		// 向Agent发送PDU
		pdu.setType(PDU.TRAP);
		snmp.send(pdu, target);
		System.out.println("----> Trap Send END <----");
	}
 
	/**
	 * 创建对象communityTarget
	 *
	 * @param targetAddress
	 * @param community
	 * @param version
	 * @param timeOut
	 * @param retry
	 * @return CommunityTarget
	 */
	public static CommunityTarget createTarget4Trap(String address) {
		CommunityTarget target = new CommunityTarget();
		target.setAddress(GenericAddress.parse(address));
		target.setVersion(DEFAULT_VERSION);
		target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
		target.setRetries(DEFAULT_RETRY);
		return target;
	}
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SnmpTrapSendDemo demo = new SnmpTrapSendDemo();
			demo.init();
			demo.sendPDU();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
	}
 
}



运行结果:
----> 初始 Trap 的IP和端口 <----
----> Trap Send END <----



同时接收器的日志变成如下:



----> Trap Receiver run ... <----
----> 开始监听端口,等待Trap message  <----
----> 开始解析ResponderEvent: <----
1.3.6.1.2.1.1.1.0 = SNMP Trap Test.see more:http://www.micmiu.com
1.3.6.1.2.1.1.3.0 = 155 days, 9:52:04.80
1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.6.3.1.1.4.3
---->  本次ResponderEvent 解析结束 <----



SNMP4j实现Trap的示例

标签:

原文地址:http://my.oschina.net/yxwblog/blog/417258

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!