关于SNMP是个什么东西??

老悍匪 发布于 2014/04/08 17:17
阅读 502
收藏 0

我看过了网上的关于snmp的介绍,知道是个简单网络管理协议,有几个问题如下:

1、snmp在java中如何使用?(求一个demo,不要说某某网站上有,那个 什么Multi**Reciever 我看过了 ,无法运行)

2、现在想学习在java中SNMP的使用和注意事项,求大牛不吝赐教,谢谢。


PS:网上关于这个的例子,都是一个版本的,贴来贴去,还是个不能运行的。。。。。。

求大家严谨!

加载中
0
LucEsape
LucEsape

package test;

import java.io.IOException;

import org.apache.log4j.Logger;
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.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;

/**
 * @author Yuer
 * 
 */
public class SnmpWalk {
	public static Logger		logger				= Logger.getLogger(SnmpWalk.class);

	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 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;

			logger.info("Host IP: " + ip);

			while (!finished) {
				VariableBinding vb = null;
				ResponseEvent responseEvent = snmp.getNext(pdu, target);

				PDU response = responseEvent.getResponse();

				if (null == response) {
					logger.info("responsePDU == null");
					finished = true;
					break;
				} else {
					vb = response.get(0);
				}
				// check finish
				finished = checkWalkFinished(targetOID, pdu, vb);
				if (!finished) {
					logger.info(vb);
					pdu.setRequestID(new Integer32(0));
					pdu.set(0, vb);
				} else {
					logger.debug("SNMP walk OID done.");
					snmp.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("SNMP walk Exception: " + e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException ex1) {
					snmp = null;
				}
			}
		}

	}

	/**
	 * 1)responsePDU == null<br>
	 * 2)responsePDU.getErrorStatus() != 0<br>
	 * 3)responsePDU.get(0).getOid() == null<br>
	 * 4)responsePDU.get(0).getOid().size() < targetOID.size()<br>
	 * 5)targetOID.leftMostCompare(targetOID.size(),responsePDU.get(0).getOid())
	 * !=0<br>
	 * 6)Null.isExceptionSyntax(responsePDU.get(0).getVariable().getSyntax())<br>
	 * 7)responsePDU.get(0).getOid().compareTo(targetOID) <= 0<br>
	 * 
	 * @param resquestPDU
	 * @param targetOID
	 * @param responsePDU
	 * @param vb
	 * @return
	 */
	private static boolean checkWalkFinished(OID targetOID,
			PDU pdu,
			VariableBinding vb) {
		boolean finished = false;
		if (pdu.getErrorStatus() != 0) {
			logger.debug("[true] responsePDU.getErrorStatus() != 0 ");
			logger.debug(pdu.getErrorStatusText());
			finished = true;
		} else if (vb.getOid() == null) {
			logger.debug("[true] vb.getOid() == null");
			finished = true;
		} else if (vb.getOid().size() < targetOID.size()) {
			logger.debug("[true] vb.getOid().size() < targetOID.size()");
			finished = true;
		} else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
			logger.debug("[true] targetOID.leftMostCompare() != 0");
			finished = true;
		} else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
			logger.debug("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
			finished = true;
		} else if (vb.getOid().compareTo(targetOID) <= 0) {
			logger.debug("[true] Variable received is not "
					+ "lexicographic successor of requested " + "one:");
			logger.debug(vb.toString() + " <= " + targetOID);
			finished = true;
		}
		return finished;

	}

	public static void main(String[] args) {

		String ip = "127.0.0.1";
		String community = "public";
		String targetOid = "";
		SnmpWalk.snmpWalk(ip, community, targetOid);
	}
}

在本机电脑上开启SNMP Service 服务

LucEsape
LucEsape
回复 @老悍匪 : 客气。snmp 一般是用来开发监控系统的。楼主结贴吧
老悍匪
老悍匪
谢谢,有反应了
0
狐狸糊涂
狐狸糊涂

找到一段code,是基于snmp4j 2.0.3的。先了解下snmp的基础,有具体问题再来问吧。

public class SnmpCLI {

	public String snmpGet(String ipAddr, String community, String oid) {
		String result = null;
		String addr = "udp:" + ipAddr + "/161";

		Address targetAddress = GenericAddress.parse(addr);
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(oid)));
		pdu.setType(PDU.GETBULK);
		pdu.setMaxRepetitions(10);

		// Set Community
		CommunityTarget communityTarget = new CommunityTarget();
		communityTarget.setCommunity(new OctetString(community));
		communityTarget.setAddress(targetAddress);
		communityTarget.setVersion(SnmpConstants.version2c);
		communityTarget.setTimeout(2000);
		communityTarget.setRetries(1);

		DefaultUdpTransportMapping udpTransportMap = null;
		Snmp snmp = null;
		try {
			// 发送同步消息
			udpTransportMap = new DefaultUdpTransportMapping();
			udpTransportMap.listen();
			snmp = new Snmp(udpTransportMap);
			ResponseEvent response = snmp.send(pdu, communityTarget);
			PDU resposePdu = response.getResponse();

			if (resposePdu == null) {
				System.out.println(ipAddr + ": Request timed out.");
			} else {
				// errorStatus = resposePdu.getErrorStatus();
				Vector<? extends VariableBinding> vars = resposePdu.getVariableBindings();
				for(VariableBinding var : vars)
				{
					System.out.println(var.getVariable());
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("获取SNMP节点状态时发生错误!", e);
		} finally {
			if (snmp != null) {
				try {
					snmp.close();
				} catch (IOException e) {
					snmp = null;
				}
			}
			if (udpTransportMap != null) {
				try {
					udpTransportMap.close();
				} catch (IOException e) {
					udpTransportMap = null;
				}
			}
		}

		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		SnmpCLI cli = new SnmpCLI();
		cli.snmpGet("10.89.110.50", "private", "1.3.6.1.4.1.4115.1.3.13.4.7.1.1.1");
	}
}



老悍匪
老悍匪
回复 @狐狸糊涂 : 谢谢
老悍匪
老悍匪
回复 @狐狸糊涂 : 我开启了 snmp trap 服务 这个 有用么
狐狸糊涂
狐狸糊涂
回复 @老悍匪 : 你本地应该是windows机器,默认应该是没有开启snmpAgent的服务,所以是不支持snmp查询的。
老悍匪
老悍匪
我给了 本地ip 提示192.168.1.123: Request timed out.
老悍匪
老悍匪
在么? 这个怎么测试 我是新手 谢谢
0
老悍匪
老悍匪

我开启了  snmp trap 服务 这个 有用么


0
amonxu
amonxu

搞了几个月的snmp,蛋疼死了,哈哈。

返回顶部
顶部