利用SNMP获取、走访节点值

该博客介绍了如何利用SNMP4J框架进行SNMP GET操作,以及使用Java SNMP Package进行SNMP WALK操作。提供了详细的代码示例,包括设置SNMP版本、协议、端口、共同体等参数,并处理响应结果。

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

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

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

Java代码 复制代码
  1. /**  
  2.  * SNMP管理类  
  3.  */  
  4. public class SnmpManager {   
  5.   
  6.     private static final Log log = LogFactory.getLog(SnmpManager.class);   
  7.        
  8.     private static int version = 0// SNMP版本, 0表示版本1   
  9.        
  10.     private static String protocol = "udp"// 监控时使用的协议   
  11.        
  12.     private static String port = "161"// 监控时使用的端口   
  13.            
  14.     /**  
  15.      * 获取SNMP节点值  
  16.      *   
  17.      * @param ipAddress 目标IP地址  
  18.      * @param community 公同体  
  19.      * @param oid 对象ID  
  20.      * @return String 监控结果代号  
  21.      * @throws AppException  
  22.      */  
  23.     @SuppressWarnings("unchecked")   
  24.     public static String snmpGet(String ipAddress, String community, String oid) throws AppException {   
  25.         String resultStat = null// 监控结果状态   
  26.            
  27.         StringBuffer address = new StringBuffer();   
  28.         address.append(protocol);   
  29.         address.append(":");   
  30.         address.append(ipAddress);   
  31.         address.append("/");   
  32.         address.append(port);   
  33.            
  34. //      Address targetAddress = GenericAddress.parse(protocol + ":" + ipAddress + "/" + port);   
  35.         Address targetAddress = GenericAddress.parse(address.toString());   
  36.         PDU pdu = new PDU();   
  37.         pdu.add(new VariableBinding(new OID(oid)));   
  38.         pdu.setType(PDU.GET);   
  39.   
  40.         // 创建共同体对象CommunityTarget   
  41.         CommunityTarget target = new CommunityTarget();   
  42.         target.setCommunity(new OctetString(community));   
  43.         target.setAddress(targetAddress);   
  44.         target.setVersion(SnmpConstants.version1);   
  45.         target.setTimeout(2000);   
  46.         target.setRetries(1);   
  47.   
  48.         DefaultUdpTransportMapping udpTransportMap = null;   
  49.         Snmp snmp = null;   
  50.         try {   
  51.             // 发送同步消息   
  52.             udpTransportMap = new DefaultUdpTransportMapping();   
  53.             udpTransportMap.listen();   
  54.             snmp = new Snmp(udpTransportMap);   
  55.             ResponseEvent response = snmp.send(pdu, target);   
  56.             PDU resposePdu = response.getResponse();   
  57.   
  58.             if (resposePdu == null) {   
  59.                 log.info(ipAddress + ": Request timed out.");   
  60.             } else {   
  61.                 //errorStatus = resposePdu.getErrorStatus();   
  62.                 Object obj = resposePdu.getVariableBindings().firstElement();   
  63.                 VariableBinding variable = (VariableBinding) obj;   
  64.                 resultStat = variable.getVariable().toString();   
  65.             }   
  66.         } catch (Exception e) {   
  67.             throw new AppException("获取SNMP节点状态时发生错误!", e);   
  68.         } finally {   
  69.             if (snmp != null) {   
  70.                 try {   
  71.                     snmp.close();   
  72.                 } catch (IOException e) {   
  73.                     snmp = null;   
  74.                 }   
  75.             }   
  76.             if (udpTransportMap != null) {   
  77.                 try {   
  78.                     udpTransportMap.close();   
  79.                 } catch (IOException e) {   
  80.                     udpTransportMap = null;   
  81.                 }   
  82.             }   
  83.         }   
  84.            
  85.         if (log.isInfoEnabled()) {   
  86.             log.info("IP:" + ipAddress + " resultStat:" + resultStat);   
  87.         }   
  88.            
  89.         return resultStat;   
  90.     }   
  91.        
  92.        
  93.     /**  
  94.      * 走访SNMP节点  
  95.      *   
  96.      * @param ipAddress 目标IP地址  
  97.      * @param community 共同体  
  98.      * @param oid 节点起始对象标志符  
  99.      * @return String[] 走方结果  
  100.      * @throws AppException  
  101.      */  
  102.     public static String[] snmpWalk(String ipAddress, String community, String oid) throws AppException {   
  103.         String[] returnValueString = null// oid走访结果数组   
  104.            
  105.         SNMPv1CommunicationInterface comInterface = null;   
  106.         try {   
  107.             InetAddress hostAddress = InetAddress.getByName(ipAddress);   
  108.             comInterface = new SNMPv1CommunicationInterface(   
  109.                     version, hostAddress, community);   
  110.             comInterface.setSocketTimeout(2000);   
  111.                
  112.             // 返回所有以oid开始的管理信息库变量值   
  113.             SNMPVarBindList tableVars = comInterface.retrieveMIBTable(oid);   
  114.             returnValueString = new String[tableVars.size()];   
  115.                
  116.             // 循环处理所有以oid开始的节点的返回值   
  117.             for (int i = 0; i < tableVars.size(); i++) {   
  118.                 SNMPSequence pair = (SNMPSequence) tableVars.getSNMPObjectAt(i); // 获取SNMP序列对象, 即(OID,value)对   
  119.                 SNMPObject snmpValue = pair.getSNMPObjectAt(1); // 获取某个节点的返回值   
  120.                 String typeString = snmpValue.getClass().getName(); // 获取SNMP值类型名   
  121.                 // 设置返回值   
  122.                 if (typeString.equals("snmp.SNMPOctetString")) {   
  123.                     String snmpString = snmpValue.toString();   
  124.                     int nullLocation = snmpString.indexOf('/0');   
  125.                     if (nullLocation >= 0)   
  126.                         snmpString = snmpString.substring(0, nullLocation);   
  127.                     returnValueString[i] = snmpString;   
  128.                 } else {   
  129.                     returnValueString[i] = snmpValue.toString();   
  130.                 }   
  131.             }   
  132.         } catch (SocketTimeoutException ste) {   
  133.             if (log.isErrorEnabled()) {   
  134.                 log.error("走访IP为" + ipAddress + ", OID为" + oid + " 时超时!");   
  135.             }   
  136.             returnValueString = null;   
  137.         } catch (Exception e) {   
  138.             throw new AppException("SNMP走访节点时发生错误!", e);   
  139.         } finally {   
  140.             if (comInterface != null) {   
  141.                 try {   
  142.                     comInterface.closeConnection();   
  143.                 } catch (SocketException e) {   
  144.                     comInterface = null;   
  145.                 }   
  146.             }   
  147.         }   
  148.            
  149.         return returnValueString;   
  150.     }   
  151. }  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值