snmp4j获取mib信息的实例(测试成功)

使用java采用SNMP协议来获取设备上的MIB信息,测试例子采用的是本机作为测试,并且系统是win7而且启用了SNMP协议。

在win7上开启SNMP协议的教程如链接所示:

http://blog.chinaunix.net/uid-24058189-id-2105677.html

在java中来操作snmp协议的jar包下载地址:

http://www.snmp4j.org

工程结构(红框为最重要的两个文件):

本例子源码(采用maven框架,不影响例子):

package mySNMP;

import java.io.IOException;
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.TransportMapping;
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.Integer32;
import org.snmp4j.smi.Null;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
 * 演示: GET单个OID值
 *
 * blog http://www.micmiu.com
 *
 * @author Michael
 */
public class SnmpData {

	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;
	}
	/*获取信息*/
	public static void snmpGet(String ip, String community, String oid) {

		CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		try {
			PDU pdu = new PDU();
			// pdu.add(new VariableBinding(new OID(new int[]
			// {1,3,6,1,2,1,1,2})));
			pdu.add(new VariableBinding(new OID(oid)));

			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			System.out.println("-------> 发送PDU <-------");
			pdu.setType(PDU.GET);
			ResponseEvent respEvent = snmp.send(pdu, target);
			System.out.println("PeerAddress:" + respEvent.getPeerAddress());
			PDU response = respEvent.getResponse();

			if (response == null) {
				System.out.println("response is null, request time out");
			} else {

				// Vector<VariableBinding> vbVect =
				// response.getVariableBindings();
				// System.out.println("vb size:" + vbVect.size());
				// if (vbVect.size() == 0) {
				// System.out.println("response vb size is 0 ");
				// } else {
				// VariableBinding vb = vbVect.firstElement();
				// System.out.println(vb.getOid() + " = " + vb.getVariable());
				// }

				System.out.println("response pdu size is " + response.size());
				for (int i = 0; i < response.size(); i++) {
					VariableBinding vb = response.get(i);
					System.out.println(vb.getOid() + " = " + vb.getVariable());
				}

			}
			System.out.println("SNMP GET one OID value finished !");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP Get Exception:" + e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}

		}
	}
	/*获取列表信息,一次获取多条信息*/
	public static void snmpGetList(String ip, String community, List<String> oidList)
	{
		CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		try {
			PDU pdu = new PDU();

			for(String oid:oidList)
			{
				pdu.add(new VariableBinding(new OID(oid)));
			}

			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			System.out.println("-------> 发送PDU <-------");
			pdu.setType(PDU.GET);
			ResponseEvent respEvent = snmp.send(pdu, target);
			System.out.println("PeerAddress:" + respEvent.getPeerAddress());
			PDU response = respEvent.getResponse();

			if (response == null) {
				System.out.println("response is null, request time out");
			} else {

				System.out.println("response pdu size is " + response.size());
				for (int i = 0; i < response.size(); i++) {
					VariableBinding vb = response.get(i);
					System.out.println(vb.getOid() + " = " + vb.getVariable());
				}

			}
			System.out.println("SNMP GET one OID value finished !");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP Get Exception:" + e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}

		}
	}
	/*异步获取信息列表*/
	public static void snmpAsynGetList(String ip, String community,List<String> oidList)
	{
		CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		try {
			PDU pdu = new PDU();

			for(String oid:oidList)
			{
				pdu.add(new VariableBinding(new OID(oid)));
			}

			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			System.out.println("-------> 发送PDU <-------");
			pdu.setType(PDU.GET);
			ResponseEvent respEvent = snmp.send(pdu, target);
			System.out.println("PeerAddress:" + respEvent.getPeerAddress());
			PDU response = respEvent.getResponse();

			/*异步获取*/
			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]:" + request);
					if (response == null) {
						System.out.println("[ERROR]: response is null");
					} else if (response.getErrorStatus() != 0) {
						System.out.println("[ERROR]: response status"
								+ response.getErrorStatus() + " Text:"
								+ response.getErrorStatusText());
					} else {
						System.out.println("Received response Success!");
						for (int i = 0; i < response.size(); i++) {
							VariableBinding vb = response.get(i);
							System.out.println(vb.getOid() + " = "
									+ vb.getVariable());
						}
						System.out.println("SNMP Asyn GetList OID finished. ");
						latch.countDown();
					}
				}
			};

			pdu.setType(PDU.GET);
			snmp.send(pdu, target, null, listener);
			System.out.println("asyn send pdu wait for response...");

			boolean wait = latch.await(30, TimeUnit.SECONDS);
			System.out.println("latch.await =:" + wait);

			snmp.close();

			System.out.println("SNMP GET one OID value finished !");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP Get Exception:" + e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}

		}
	}
	/*获取表格*/
	public static void snmpWalk(String ip, String community, String targetOid)
	{
		CommunityTarget target = createDefault(ip, community);
		TransportMapping transport = null;
		Snmp snmp = null;
		try {
			transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			transport.listen();

			PDU pdu = new PDU();
			OID targetOID = new OID(targetOid);
			pdu.add(new VariableBinding(targetOID));

			boolean finished = false;
			System.out.println("----> demo start <----");
			while (!finished) {
				VariableBinding vb = null;
				ResponseEvent respEvent = snmp.getNext(pdu, target);

				PDU response = respEvent.getResponse();

				if (null == response) {
					System.out.println("responsePDU == null");
					finished = true;
					break;
				} else {
					vb = response.get(0);
				}
				// check finish
				finished = checkWalkFinished(targetOID, pdu, vb);
				if (!finished) {
					System.out.println("==== walk each vlaue :");
					System.out.println(vb.getOid() + " = " + vb.getVariable());

					// Set up the variable binding for the next entry.
					pdu.setRequestID(new Integer32(0));
					pdu.set(0, vb);
				} else {
					System.out.println("SNMP walk OID has finished.");
					snmp.close();
				}
			}
			System.out.println("----> demo end <----");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP walk Exception: " + e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}
		}
	}

	private static boolean checkWalkFinished(OID targetOID, PDU pdu,
			VariableBinding vb) {
		boolean finished = false;
		if (pdu.getErrorStatus() != 0) {
			System.out.println("[true] responsePDU.getErrorStatus() != 0 ");
			System.out.println(pdu.getErrorStatusText());
			finished = true;
		} else if (vb.getOid() == null) {
			System.out.println("[true] vb.getOid() == null");
			finished = true;
		} else if (vb.getOid().size() < targetOID.size()) {
			System.out.println("[true] vb.getOid().size() < targetOID.size()");
			finished = true;
		} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
			System.out.println("[true] targetOID.leftMostCompare() != 0");
			finished = true;
		} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
			System.out
					.println("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
			finished = true;
		} else if (vb.getOid().compareTo(targetOID) <= 0) {
			System.out.println("[true] Variable received is not "
					+ "lexicographic successor of requested " + "one:");
			System.out.println(vb.toString() + " <= " + targetOID);
			finished = true;
		}
		return finished;

	}
	/*异步获取表格*/
	public static void snmpAsynWalk(String ip, String community, String oid)
	{
		final CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		try {
			System.out.println("----> demo start <----");

			DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();

			final PDU pdu = new PDU();
			final OID targetOID = new OID(oid);
			final CountDownLatch latch = new CountDownLatch(1);
			pdu.add(new VariableBinding(targetOID));

			ResponseListener listener = new ResponseListener() {
				public void onResponse(ResponseEvent event) {
					((Snmp) event.getSource()).cancel(event.getRequest(), this);

					try {
						PDU response = event.getResponse();
						// PDU request = event.getRequest();
						// System.out.println("[request]:" + request);
						if (response == null) {
							System.out.println("[ERROR]: response is null");
						} else if (response.getErrorStatus() != 0) {
							System.out.println("[ERROR]: response status"
									+ response.getErrorStatus() + " Text:"
									+ response.getErrorStatusText());
						} else {
							System.out
									.println("Received Walk response value :");
							VariableBinding vb = response.get(0);

							boolean finished = checkWalkFinished(targetOID,
									pdu, vb);
							if (!finished) {
								System.out.println(vb.getOid() + " = "
										+ vb.getVariable());
								pdu.setRequestID(new Integer32(0));
								pdu.set(0, vb);
								((Snmp) event.getSource()).getNext(pdu, target,
										null, this);
							} else {
								System.out
										.println("SNMP Asyn walk OID value success !");
								latch.countDown();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						latch.countDown();
					}

				}
			};

			snmp.getNext(pdu, target, null, listener);
			System.out.println("pdu 已发送,等到异步处理结果...");

			boolean wait = latch.await(30, TimeUnit.SECONDS);
			System.out.println("latch.await =:" + wait);
			snmp.close();

			System.out.println("----> demo end <----");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SNMP Asyn Walk Exception:" + e);
		}
	}
	/*设置信息*/
	public static void setPDU(String ip,String community,String oid) throws IOException
	{
		CommunityTarget target = createDefault(ip, community);
		Snmp snmp = null;
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(oid),new OctetString("shangrao")));
		pdu.setType(PDU.SET);

		DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		snmp.listen();
		System.out.println("-------> 发送PDU <-------");
		snmp.send(pdu, target);
		snmp.close();
	}
}

测试例子

/**
 *
 */
package mySNMP;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
 * @filename SnmpGet.java
 * @author code by jianghuiwen
 * @mail [email protected]
 *
 * 下午2:21:53
 */
public class TestSnmpGet {

	@Test
	public void testGet()
	{
		String ip = "127.0.0.1";
		String community = "public";
		String oidval = "1.3.6.1.2.1.1.6.0";
		SnmpData.snmpGet(ip, community, oidval);
	}

	public void testGetList()
	{
		String ip = "127.0.0.1";
		String community = "public";
		List<String> oidList=new ArrayList<String>();
		oidList.add("1.3.6.1.2.1.1.5.0");
		oidList.add("1.3.6.1.2.1.1.7.0");
		SnmpData.snmpGetList(ip, community, oidList);
	}

	public void testGetAsyList()
	{
		String ip = "127.0.0.1";
		String community = "public";
		List<String> oidList=new ArrayList<String>();
		oidList.add("1.3.6.1.2.1.1.5.0");
		oidList.add("1.3.6.1.2.1.1.7.0");
		SnmpData.snmpAsynGetList(ip, community, oidList);

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

	public void testWalk()
	{
		String ip = "127.0.0.1";
		String community = "public";
		String targetOid = "1.3.6.1.2.1.25.4.2.1.2";
		SnmpData.snmpWalk(ip, community, targetOid);
	}

	public void testAsyWalk()
	{
		String ip = "127.0.0.1";
		String community = "public";

		// 异步采集数据
		SnmpData.snmpAsynWalk(ip, community, "1.3.6.1.2.1.25.4.2.1.2");
	}

	@Test
	public void testSetPDU() throws Exception
	{
		String ip = "127.0.0.1";
		String community = "public";

		SnmpData.setPDU(ip, community, "1.3.6.1.2.1.1.6.0");
	}
}

输出结果

时间: 2024-10-14 01:21:02

snmp4j获取mib信息的实例(测试成功)的相关文章

【Python】[面性对象编程] 获取对象信息,实例属性和类属性

获取对象信息1.使用isinstance()判断class类型2.dir() 返回一个对象的所有属性和方法3.如果试图获取不存在的对象会抛出异常[AttributeError]4.正确利用对象内置函数的例子: def readImage(fp): if hasattr(fp,"read"): return readData(fp) return None 实例属性和类属性1.一句话,Python是动态语言,根据类创建的实例可以任意绑定属性.    注意:实例属性和雷属性的名字要保持不一

微信快速开发框架V2.3--增加语音识别及网页获取用户信息(八),代码已更新至Github

不知不觉,版本以每周更新一次的脚步进行着,接下来应该是重构我的代码及框架的结构,有朋友反应代码有点乱,确实如此,当时写的时候只是按照订阅号来写的,后来才慢慢增加到支持API接口.目前还在开发第三方微信平台,旨在使用户能够无需自己开发就能简易搭建微信平台. 更新内容 1.增加支持语音识别 2.增加"网页授权获取用户基本信息" 语音识别其实是对Voice信息的一个扩展,您必须启用语音识别功能,启用后会在VoiceMessage中增加一个Recongnition字段,我们可以判断这个字段的内

Java实践-远程调用Shell脚本并获取输出信息

1.添加依赖 <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>262</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId&g

iOS利用HealthKit框架从健康app中获取步数信息

微信和QQ的每日步数最近十分火爆,我就想为自己写的项目中添加一个显示每日步数的功能,上网一搜好像并有相关的详细资料,自己动手丰衣足食. 统计步数信息并不需要我们自己去实现,iOS自带的健康app已经为我们统计好了步数数据 我们只要使用HealthKit框架从健康app中获取这个数据信息就可以了 这篇文章对HealthKit框架进行了简单的介绍:http://www.cocoachina.com/ios/20140915/9624.html 对HealthKit框架有了简单的了解后我们就可以开始了

Android之QQ授权登录获取用户信息

有时候我们开发的app须要方便用户简单登录.能够让用户使用自己的qq.微信.微博登录到我们自己开发的app. 今天就在这里总结一下怎样在自己的app中集成QQ授权登录获取用户信息的功能. 首先我们打开腾讯开发平台这个网页,点击---->移动应用---->创建应用,成功创建应用后.能够产生我们须要的App ID和App Key,例如以下图所看到的: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmVhcl9odWFuZ3poZW4=/font/5a6

C# 网络编程之通过豆瓣API获取书籍信息(一)

这篇文章主要是讲述如何通过豆瓣API获取书籍的信息,起初看到这个内容我最初的想法是在"C# 网络编程之网页简单下载实现"中通过HttpWebResponse类下载源码,再通过正则表达式分析获取结点标签得到信息.但后来发现可以通过豆瓣API提供的编程接口实现. 该文章仅是基础性C#网络编程文章,尝试测试了下豆瓣API,并没什么高深的内容.但希望对大家有所帮助,仅供学习. (警告:文章仅供参考,提供一种想法,否则访问多次-10次被403 forbidden莫怪.建议认证使用豆瓣API) 一

百度地图_根据地图上标记位置获取街道信息,以及经纬度信息

Class:服务类/Geocoder Class:服务类/GeocoderResult <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>百度地图Demo</title> <script type="text/jav

通过window.navigator对象获取地理位置信息并在百度地图上显示

通过window.navigator对象获取地理位置信息 Geolocation API:用户可共享地理位置,并在Web应用的协助下享用位置感知服务(location-aware services) window.navigator下的geolocation 对象的 getCurrentPosition 方法可以获取当前位置.getCurrentPosition 方法将发起对位置信息的异步请求并将立即返回.如果该请求成功完成,则调用用来实现位置数据接收的成功回调. 下面演示如何调用 getCur

纯JAVA环境获取APK信息(包名,版本,版本号,大小,权限...),纯JAVA语言编写PC端获取APK信息

纯JAVA环境获取APK信息:包名,版本,版本号,大小,权限... 纯Java环境获取APK信息需要两个包:AXMLPrinter2.jar 跟jdom.jar,用于反编译XML和解析XML的 项目目录 这个类是获取APK信息的 public class ApkUtil { private static final Namespace NS = Namespace.getNamespace("http://schemas.android.com/apk/res/android"); @