论坛首页 Java企业应用论坛

利用SNMP4J实现Snmp Trap完整例子

浏览 55576 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-01-02  

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

 

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;

/**
 * 本类用于监听代理进程的Trap信息
 * 
 * @author zhanjia
 *
 */
public class MultiThreadedTrapReceiver implements CommandResponder {

	private MultiThreadedMessageDispatcher dispatcher;
	private Snmp snmp = null;
	private Address listenAddress;
	private ThreadPool threadPool;

	public MultiThreadedTrapReceiver() {
		// BasicConfigurator.configure();
	}

	private void init() throws UnknownHostException, IOException {
		threadPool = ThreadPool.create("Trap", 2);
		dispatcher = new MultiThreadedMessageDispatcher(threadPool,
				new MessageDispatcherImpl());
		listenAddress = GenericAddress.parse(System.getProperty(
				"snmp4j.listenAddress", "udp:192.168.1.23/162")); // 本地IP与监听端口
		TransportMapping transport;
		// 对TCP与UDP协议进行处理
		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() {
		try {
			init();
			snmp.addCommandResponder(this);
			System.out.println("开始监听Trap信息!");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 实现CommandResponder的processPdu方法, 用于处理传入的请求、PDU等信息
	 * 当接收到trap时,会自动进入这个方法
	 * 
	 * @param respEvnt
	 */
	public void processPdu(CommandResponderEvent respEvnt) {
		// 解析Response
        if (respEvnt != null && respEvnt.getPDU() != null) {
        	Vector<VariableBinding> recVBs = respEvnt.getPDU().getVariableBindings();
           	for (int i = 0; i < recVBs.size(); i++) {
            	VariableBinding recVB = recVBs.elementAt(i);
               	System.out.println(recVB.getOid() + " : " + recVB.getVariable());
      		}
		}
	}

	public static void main(String[] args) {
		MultiThreadedTrapReceiver multithreadedtrapreceiver = new MultiThreadedTrapReceiver();
		multithreadedtrapreceiver.run();
	}

}

 

 

import java.io.IOException;
import java.util.Vector;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
 * 本类用于向管理进程发送Trap信息
 * 
 * @author zhanjia
 *
 */
public class SnmpUtilSendTrap {

	private Snmp snmp = null;

	private Address targetAddress = null;

	public void initComm() throws IOException {

		// 设置管理进程的IP和端口
		targetAddress = GenericAddress.parse("udp:192.168.1.23/162");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();

	}

	/**
	 * 向管理进程发送Trap报文
	 * 
	 * @throws IOException
	 */
	public void sendPDU() throws IOException {

		// 设置 target
		CommunityTarget target = new CommunityTarget();
		target.setAddress(targetAddress);

		// 通信不成功时的重试次数
		target.setRetries(2);
		// 超时时间
		target.setTimeout(1500);
		// snmp版本
		target.setVersion(SnmpConstants.version2c);

		// 创建 PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),
				new OctetString("SnmpTrap")));
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"),
				new OctetString("JavaEE")));
		pdu.setType(PDU.TRAP);

		// 向Agent发送PDU,并接收Response
		ResponseEvent respEvnt = snmp.send(pdu, target);

		// 解析Response
		if (respEvnt != null && respEvnt.getResponse() != null) {
			Vector<VariableBinding> recVBs = respEvnt.getResponse()
			.getVariableBindings();
			for (int i = 0; i < recVBs.size(); i++) {
				VariableBinding recVB = recVBs.elementAt(i);
				System.out.println(recVB.getOid() + " : " + recVB.getVariable());
			}
		}
	}

	public static void main(String[] args) {
		try {
			SnmpUtilSendTrap util = new SnmpUtilSendTrap();
			util.initComm();
			util.sendPDU();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

 

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

 

   发表时间:2009-04-21  
http://publib.boulder.ibm.com/infocenter/tivihelp/v8r1/index.jsp?topic=/com.ibm.netcool_OMNIbus.doc/gateways/snmp/snmp/wip/concept/snmp_intro.html

有人做过这方面吗?
0 请登录后投票
   发表时间:2009-08-27  
SnmpUtilSendTrap 中冒失必须得设置 sysTime和trapId吧
 //必须设定第一个变量为sysUpTime
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(new UnsignedInteger32(1000).toLong())));

//设定第二个变量snmpTrapOID
        pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(".1.2.156.112546.16.0.1")));
否者的话,会出现解析不了的错误。
另外Trap没有返回信息,所以也没必要处理 Response
zhanjia 写道

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

 

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;

/**
 * 本类用于监听代理进程的Trap信息
 * 
 * @author zhanjia
 *
 */
public class MultiThreadedTrapReceiver implements CommandResponder {

	private MultiThreadedMessageDispatcher dispatcher;
	private Snmp snmp = null;
	private Address listenAddress;
	private ThreadPool threadPool;

	public MultiThreadedTrapReceiver() {
		// BasicConfigurator.configure();
	}

	private void init() throws UnknownHostException, IOException {
		threadPool = ThreadPool.create("Trap", 2);
		dispatcher = new MultiThreadedMessageDispatcher(threadPool,
				new MessageDispatcherImpl());
		listenAddress = GenericAddress.parse(System.getProperty(
				"snmp4j.listenAddress", "udp:192.168.1.23/162")); // 本地IP与监听端口
		TransportMapping transport;
		// 对TCP与UDP协议进行处理
		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() {
		try {
			init();
			snmp.addCommandResponder(this);
			System.out.println("开始监听Trap信息!");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 实现CommandResponder的processPdu方法, 用于处理传入的请求、PDU等信息
	 * 当接收到trap时,会自动进入这个方法
	 * 
	 * @param respEvnt
	 */
	public void processPdu(CommandResponderEvent respEvnt) {
		// 解析Response
        if (respEvnt != null && respEvnt.getPDU() != null) {
        	Vector<VariableBinding> recVBs = respEvnt.getPDU().getVariableBindings();
           	for (int i = 0; i < recVBs.size(); i++) {
            	VariableBinding recVB = recVBs.elementAt(i);
               	System.out.println(recVB.getOid() + " : " + recVB.getVariable());
      		}
		}
	}

	public static void main(String[] args) {
		MultiThreadedTrapReceiver multithreadedtrapreceiver = new MultiThreadedTrapReceiver();
		multithreadedtrapreceiver.run();
	}

}

 

 

import java.io.IOException;
import java.util.Vector;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
 * 本类用于向管理进程发送Trap信息
 * 
 * @author zhanjia
 *
 */
public class SnmpUtilSendTrap {

	private Snmp snmp = null;

	private Address targetAddress = null;

	public void initComm() throws IOException {

		// 设置管理进程的IP和端口
		targetAddress = GenericAddress.parse("udp:192.168.1.23/162");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();

	}

	/**
	 * 向管理进程发送Trap报文
	 * 
	 * @throws IOException
	 */
	public void sendPDU() throws IOException {

		// 设置 target
		CommunityTarget target = new CommunityTarget();
		target.setAddress(targetAddress);

		// 通信不成功时的重试次数
		target.setRetries(2);
		// 超时时间
		target.setTimeout(1500);
		// snmp版本
		target.setVersion(SnmpConstants.version2c);

		// 创建 PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),
				new OctetString("SnmpTrap")));
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"),
				new OctetString("JavaEE")));
		pdu.setType(PDU.TRAP);

		// 向Agent发送PDU,并接收Response
		ResponseEvent respEvnt = snmp.send(pdu, target);

		// 解析Response
		if (respEvnt != null && respEvnt.getResponse() != null) {
			Vector<VariableBinding> recVBs = respEvnt.getResponse()
			.getVariableBindings();
			for (int i = 0; i < recVBs.size(); i++) {
				VariableBinding recVB = recVBs.elementAt(i);
				System.out.println(recVB.getOid() + " : " + recVB.getVariable());
			}
		}
	}

	public static void main(String[] args) {
		try {
			SnmpUtilSendTrap util = new SnmpUtilSendTrap();
			util.initComm();
			util.sendPDU();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

 

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

 

 

0 请登录后投票
   发表时间:2009-11-10  
谢谢你的示例!!我现在有个疑问:threadPool = ThreadPool.create("Trap", 2);  
上面这句是使用线程池创建了2个等待trap的线程,如果成千个trap发送过来,这两个线程都被用光了,会出现什么情况?? 线程池会不会自动增加线程?? 谢谢!
0 请登录后投票
   发表时间:2009-11-11  
那就处于等待状态啊,类似数据库的连接池差不多,如果都消耗光了,那只能一个个排队了
3 请登录后投票
   发表时间:2009-11-11  
做网络监控是很有前途的, 云计算服务商将来将非常依赖网络监控系统。庞大的计算机集群和网络资源是需要非常好的监控系统的。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics