snmp通过get方式异步获取oid

ResponseListener 是能够实现异步get获取数据的核心部分。用到了Java多线程编程中的实现Runnable接口(或者使用线程池),Java的countDownLatch类。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
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;

/**
 * 
 * 多线程方式SNMP异步get获取数据,实现Runnable接口
 */
public class SnmpGetAsyn001  implements Runnable{

	/*SNMP get所需要的数据*/
	private String ip;
	private String community;
	private List<String> oids;
	
	private Thread thread;
	
	/**
	 * @param ip
	 * @param thread
	 * @param community
	 * @param oids
	 */
	/*把需要传入SNMP get操作的数据在线程初始化时传入*/
	public SnmpGetAsyn001(String ip, String community, List<String> oids) {
		super();
		this.ip = ip;
		this.community = community;
		this.oids = oids;
	}
	
	/*以下依次为:snmp协议版本v2c、通信协议udp、响应方接收请求端口号161、连接超时时间3秒、重连次数*/
	public static final int DEFAULT_VERSION = SnmpConstants.version2c;
	public static final String DEFAULT_PROTOCOL = "udp";
	public static final int DEFAULT_PORT = 161;
	public static final long DEFAULT_TIMEOUT = 3 * 1000L;
	public static final int DEFAULT_RETRY = 3;
 
	/**
	 * 创建对象communityTarget
	 *
	 * @param targetAddress
	 * @param community
	 * @param version
	 * @param timeOut
	 * @param retry
	 * @return CommunityTarget
	 */
	public static CommunityTarget createDefault(String ip, String community) {
		Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip
				+ "/" + DEFAULT_PORT);
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(address);
		target.setVersion(DEFAULT_VERSION);
		target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
		target.setRetries(DEFAULT_RETRY);
		return target;
	}
	
	/**
	 * 异步采集信息
	 *
	 * @param ip
	 * @param community
	 * @param oid
	 */
	public static void snmpAsynGetList(String ip, String community,
			List<String> oidList) {
		//CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		try {
			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
 
			CommunityTarget target = createDefault(ip, community);
			
			//添加用户
            /*UsmUser user = new UsmUser(new OctetString("nqctek01"),
                    //AuthMD5.ID, new OctetString(pw), PrivDES.ID, new OctetString(pk));
                    AuthSHA.ID, new OctetString("nqctekps01"), PrivAES128.ID, new OctetString("nqctekpk01"));
            snmp.getUSM().addUser(new OctetString("nqctek01"), user);*/
			
			
			PDU pdu = new PDU();
			for (String oid : oidList) {
				pdu.add(new VariableBinding(new OID(oid)));
			}
 
			final CountDownLatch latch = new CountDownLatch(1);
			ResponseListener listener = new ResponseListener() {
				public void onResponse(ResponseEvent event) {
					((Snmp) event.getSource()).cancel(event.getRequest(), this);
					PDU response = event.getResponse();
					PDU request = event.getRequest();
					System.out.println("请求:" + request);
					if (response == null) {
						System.out.println("错误一: 响应为空!");
					} else if (response.getErrorStatus() != 0) {
						System.out.println("错误二: 错误响应状态");
								//+ response.getErrorStatus() + " Text:"
								//+ response.getErrorStatusText());
					} else {
						System.out.println("响应成功!");
						for (int i = 0; i < response.size(); i++) {
							VariableBinding vb = response.get(i);
							System.out.println(vb.getOid() + " = "
									+ vb.getVariable());
						}
						System.out.println("SNMP异步获取OID参数,执行结束!");
						latch.countDown();
					}
				}
			};
 
			pdu.setType(PDU.GET);
			snmp.send(pdu, target, null, listener);
			System.out.println("异步发送pdu等待响应!"+ip);
 
			boolean wait = latch.await(30, TimeUnit.SECONDS);
			System.out.println("等待时间latch.await =:" + wait);
 
			snmp.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP Asyn GetList Exception:" + e);
		}
 
	}
	
	/**
	 *
	 * @param args
	 */
	public static void main(String[] args) {

		String ip1 = "192.168.10.129";
		String ip2 = "192.168.10.111";
		String community = "public";

		List<String> oidList = new ArrayList<String>();
		oidList.add(".1.3.6.1.2.1.1.1.0");
		oidList.add(".1.3.6.1.2.1.1.3.0");
		oidList.add(".1.3.6.1.2.1.1.5.0");
		// 异步采集数据
		SnmpGetAsyn001 snmpGetAsyn001_1 = new SnmpGetAsyn001(ip2, community, oidList);
		snmpGetAsyn001_1.start();
		
		SnmpGetAsyn001 snmpGetAsyn001_2 = new SnmpGetAsyn001(ip1, community, oidList);
		snmpGetAsyn001_2.start();

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		snmpAsynGetList(ip, community, oids);
	}
	
	public void start () {
	      if (thread == null) {
	    	  thread = new Thread (this);
	    	  thread.start();
	      }
	   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值