论坛首页 Java企业应用论坛

利用SNMP获取、走访节点值

浏览 16451 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-12-13   最后修改:2008-12-13

      本例用到两个开源包,snmpget使用SNMP4J框架,snmpwalk使用Java SNMP Package开源包,下载地址分别为:

http://www.snmp4j.org/html/download.html

http://gicl.cs.drexel.edu/people/sevy/snmp/

/**
 * SNMP管理类
 */
public class SnmpManager {

	private static final Log log = LogFactory.getLog(SnmpManager.class);
	
	private static int version = 0; // SNMP版本, 0表示版本1
	
	private static String protocol = "udp"; // 监控时使用的协议
	
	private static String port = "161"; // 监控时使用的端口
		
	/**
	 * 获取SNMP节点值
	 * 
	 * @param ipAddress 目标IP地址
	 * @param community 公同体
	 * @param oid 对象ID
	 * @return String 监控结果代号
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public static String snmpGet(String ipAddress, String community, String oid) throws AppException {
		String resultStat = null; // 监控结果状态
		
		StringBuffer address = new StringBuffer();
		address.append(protocol);
		address.append(":");
		address.append(ipAddress);
		address.append("/");
		address.append(port);
		
//		Address targetAddress = GenericAddress.parse(protocol + ":" + ipAddress + "/" + port);
		Address targetAddress = GenericAddress.parse(address.toString());
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(oid)));
		pdu.setType(PDU.GET);

		// 创建共同体对象CommunityTarget
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString(community));
		target.setAddress(targetAddress);
		target.setVersion(SnmpConstants.version1);
		target.setTimeout(2000);
		target.setRetries(1);

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

			if (resposePdu == null) {
				log.info(ipAddress + ": Request timed out.");
			} else {
				//errorStatus = resposePdu.getErrorStatus();
				Object obj = resposePdu.getVariableBindings().firstElement();
				VariableBinding variable = (VariableBinding) obj;
				resultStat = variable.getVariable().toString();
			}
		} catch (Exception e) {
			throw new AppException("获取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;
				}
			}
		}
		
		if (log.isInfoEnabled()) {
			log.info("IP:" + ipAddress + " resultStat:" + resultStat);
		}
		
		return resultStat;
	}
	
	
	/**
	 * 走访SNMP节点
	 * 
	 * @param ipAddress 目标IP地址
	 * @param community 共同体
	 * @param oid 节点起始对象标志符
	 * @return String[] 走方结果
	 * @throws AppException
	 */
	public static String[] snmpWalk(String ipAddress, String community, String oid) throws AppException {
		String[] returnValueString = null; // oid走访结果数组
		
		SNMPv1CommunicationInterface comInterface = null;
		try {
			InetAddress hostAddress = InetAddress.getByName(ipAddress);
			comInterface = new SNMPv1CommunicationInterface(
					version, hostAddress, community);
			comInterface.setSocketTimeout(2000);
			
			// 返回所有以oid开始的管理信息库变量值
			SNMPVarBindList tableVars = comInterface.retrieveMIBTable(oid);
			returnValueString = new String[tableVars.size()];
			
			// 循环处理所有以oid开始的节点的返回值
			for (int i = 0; i < tableVars.size(); i++) {
				SNMPSequence pair = (SNMPSequence) tableVars.getSNMPObjectAt(i); // 获取SNMP序列对象, 即(OID,value)对
				SNMPObject snmpValue = pair.getSNMPObjectAt(1); // 获取某个节点的返回值
				String typeString = snmpValue.getClass().getName(); // 获取SNMP值类型名
				// 设置返回值
				if (typeString.equals("snmp.SNMPOctetString")) {
					String snmpString = snmpValue.toString();
					int nullLocation = snmpString.indexOf('\0');
					if (nullLocation >= 0)
						snmpString = snmpString.substring(0, nullLocation);
					returnValueString[i] = snmpString;
				} else {
					returnValueString[i] = snmpValue.toString();
				}
			}
		} catch (SocketTimeoutException ste) {
			if (log.isErrorEnabled()) {
				log.error("走访IP为" + ipAddress + ", OID为" + oid + " 时超时!");
			}
			returnValueString = null;
		} catch (Exception e) {
			throw new AppException("SNMP走访节点时发生错误!", e);
		} finally {
			if (comInterface != null) {
				try {
					comInterface.closeConnection();
				} catch (SocketException e) {
					comInterface = null;
				}
			}
		}
		
		return returnValueString;
	}
}

 

 

 

 

 

 

   发表时间:2008-12-15  
为何不用snmphibernate呢
0 请登录后投票
   发表时间:2008-12-20  
ffyahoo 写道

为何不用snmphibernate呢

没听过这东东, 有空可以试试
0 请登录后投票
   发表时间:2009-06-27  
PlayGod1984 写道
大侠,你为什么不写一个测试用例,我初学,不知道你的community是干啥的

找找"简单网络管理协议SNMP"的资料看看吧,看了就会明白了
0 请登录后投票
   发表时间:2009-10-08  
LZ,您的方法snmpWalk()获取OID“1.3.6.1.2.1.2.2.1.6”的结果是乱码。其他的都不会问题。【OID“1.3.6.1.2.1.2.2.1.6”为ifPhysAddress,设备上的MAC地址.】
0 请登录后投票
   发表时间:2009-10-08  
xdqcx 写道
LZ,您的方法snmpWalk()获取OID“1.3.6.1.2.1.2.2.1.6”的结果是乱码。其他的都不会问题。【OID“1.3.6.1.2.1.2.2.1.6”为ifPhysAddress,设备上的MAC地址.】


问题已经解决了:MAC地址显示问题 ((SNMPOctetString)snmpValue).toHexString(); OK!


snmpwalk()OID节点下数据量大的时候经常出现异常“java.net.SocketTimeoutException: Receive timed out”。comInterface.setSocketTimeout(time);将time设置大一点也不起作用。


0 请登录后投票
论坛首页 Java企业应用版

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