专业级的SNMP框架---SNMP4J

 
  • SNMP4J简介
相比SNMP PACKAGE API 比较低的门槛和简单的功能,SNMP4J则是完全专业级的框架.他的SNMP-TARGET-PDU的三点结构更科学更严谨,完善的PDU数据引擎也是业界的一种潮流.SNMP4J的强大体现在他对SNMPV3标准下基于用户安全(USM)方式的认证,加密,和对Agent功能的强大支持.

  • SNMP4J基本GET和GETNEXT功能
1.先建立一个工具类,主要是对SNMP,TARGET,PDU的三个SNMP4J基本类的实例化
注:出于简化,本例去掉了SNMPV3的支持,以下代码只支持SNMPV1和SNMPV2C
public class Snmp4JHelper {
   
   
      public static Snmp createSnmpSession(Address address) throws IOException {
       
        // new TransportMapping object 
        AbstractTransportMapping transport;
        if (address instanceof TcpAddress) {
          transport = new DefaultTcpTransportMapping();
        }
        else {
          transport = new DefaultUdpTransportMapping();
        }
       
        // new Snmp object
        Snmp snmp =  new Snmp(transport);

        return snmp;
      }
 
     
      public static Target createTarget(Address address,OctetString community) {
           
          CommunityTarget target = new CommunityTarget();
         
          target.setAddress(address);
          target.setCommunity(community);
          return target;

      }
     
      public static PDU createPDU(int pduType) {
         
          PDU request;

          if (pduType == PDU.V1TRAP) {
            request = new PDUv1();  
          }
          else {
            request = new PDU();
          }
         
          request.setType(pduType);
          return request;
    }
几个工具方法
   
    public static OctetString createOctetString(String s) {
        OctetString octetString;
        if (s.startsWith("0x")) {
          octetString = OctetString.fromHexString(s.substring(2), ':');
        }
        else {
          octetString = new OctetString(s);
        }
        return octetString;
     
  
   
    public static Address getAddress(String transportAddress) {   
           
            // 如果有冒号存在,就是"udp:xxx.xxx.xxx.xxx"的格式,分离出协议和地址
            int colon = transportAddress.indexOf(':');
            String transprotocol = "udp";
            if (colon > 0) {
              transprotocol = transportAddress.substring(0, colon);
              transportAddress = transportAddress.substring(colon+1);
            }
           
            // append default port follow end of transportAddress
            if (transportAddress.indexOf('/') < 0) {
              transportAddress += "/161";
            }
           
            if (transprotocol.equalsIgnoreCase("udp")) {
              return new UdpAddress(transportAddress);
            }
            else if (transprotocol.equalsIgnoreCase("tcp")) {
              return new TcpAddress(transportAddress);
            }
            throw new IllegalArgumentException("Unknown transprotocol "+transprotocol);
          }

2.定义Snmp Engine,负责维护基本的Snmp连接
public class SnmpV1V2cEngine {

    private Snmp snmp;
    private Target target;

    private Address address;
    private OctetString community = new OctetString("public");
    private int version = SnmpConstants.version2c;

    private int retries = 1;
    private int timeout = 1000;
    private int maxSizeResponsePDU = 65535;

    public SnmpV1V2cEngine(String address, String community) {
        this(address, community,null);
    }

    public SnmpV1V2cEngine(String address, String community,Integer version) {
        super();
        this.address = Snmp4JHelper.getAddress(address);
        this.community = Snmp4JHelper.createOctetString(community);
        if( null != version)
            this.version = version;
        try {
            snmpInitial();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public Target getTarget() {
        return target;
    }

    public void setTarget(Target target) {
        this.target = target;
    }

    /

    private void snmpInitial() throws IOException {
        // 建立Snmp对象
        this.snmp = Snmp4JHelper.createSnmpSession(address);

        // 建立Target对象
        this.target = Snmp4JHelper.createTarget(address, community);

        target.setVersion(version);
        target.setRetries(retries);
        target.setTimeout(timeout);
        target.setMaxSizeRequestPDU(maxSizeResponsePDU);

        snmp.listen();
    }

    public void close() {
        if (null != snmp) {
            try {
                snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            snmp = null;
        }
    }

    public void finalize() {
        close();
    }

    public ResponseEvent sendRequest(PDU request)
            throws IOException {
        return snmp.send(request, this.target);
    }

}


3.SnmpGET 和 SnmpGETNEXT代码
public class SNMPget {
       
    public static VariableBinding get(String remoteIPAddress,String remoteCommunity, String oid) throws Exception {
       
        // 初始化engine,建立snmp对象和target对象
        SnmpV1V2cEngine engine = new SnmpV1V2cEngine(remoteIPAddress,remoteCommunity);

        // 建立PDU对象
        PDU request = Snmp4JHelper.createPDU(PDU.GET);
       
        request.add(new VariableBinding(new OID(oid)));
       
        // 发起snmp request
        ResponseEvent respEvent = engine.sendRequest(request);
       
        VariableBinding tempV = null;
       
        if (respEvent.getResponse() == null) {
            // request timed out
            System.out.println("response is null");
         }else {
             System.out.println("Received response from: "+respEvent.getPeerAddress());
             tempV = (VariableBinding)respEvent.getResponse().getVariableBindings().get(0);
         }
       
        engine.finalize();
       
        return tempV;

    }
    public static SortedMap getNext(String remoteIPAddress,String remoteCommunity
                    , String baseOid) throws IOException {
       
        // 初始化,建立snmp对象和target对象
        SnmpV1V2cEngine engine = new SnmpV1V2cEngine(remoteIPAddress,remoteCommunity);
       
        //
        SortedMap map = new TreeMap();

        String currentOid = baseOid;
       
        while (true) {

            // 建立PDU对象
            PDU request = Snmp4JHelper.createPDU(PDU.GETNEXT);
            // 用currentOid 发snmp request
            request.add(new VariableBinding(new OID(currentOid)));

            // 发起snmp request
            ResponseEvent respEvent = engine.sendRequest(request);

           
            if (respEvent.getResponse() == null) {
                // request timed out
                System.out.println("response is null");
             }else {
                 VariableBinding tempV = null;
            Vector<VariableBinding> responseVB = respEvent.getResponse().getVariableBindings();
                 
                 if(1 == responseVB.size()){
                    tempV = responseVB.elementAt(0);
                    //  snmp request获取的结果,再赋值给currentOid,形成类似递归的效果
                    currentOid = tempV.getOid().toString();
                    String value = tempV.getVariable().toString().trim();
                   
                    // get ifindex from oid
                    // get the last word after a "."
                    if (currentOid.startsWith(baseOid)) {
                        // extract interface number from oid
                        int lastDot = currentOid.lastIndexOf(".");
                        String indexStr = currentOid.substring(lastDot + 1);
                        int index = Integer.parseInt(indexStr);
                       
                        // store interface description
                        map.put(new Integer(index), value);
                    } else {
                        // 如果获取的oid不再startsWith baseOid,就终止循环
                        break; 
                    }
                   
                  // end of if
                   
             }// end of if
                           
        } // end of while

       
        engine.finalize();
        return map;
    }
    public static void main(String[] args) throws Exception {
        Map<String,String> oidMap = new HashMap<String,String>();
        oidMap.put("sysDescr","1.3.6.1.2.1.1.1.0");
        oidMap.put("ifDescr","1.3.6.1.2.1.2.2.1.2");
       
        String host = "192.168.0.100/161";
        String community = "public";
       
        System.out.println("==================get测试=====================");
        VariableBinding resp = SNMPget.get(host,community,oidMap.get("sysDescr"));
        System.out.println(resp.getOid()+":"+resp.getVariable());
       
        System.out.println("==================getNext测试=================");
        SortedMap map = SNMPget.getNext(host,community,oidMap.get("ifDescr"));
        System.out.println("共"+map.size()+"个接口");
        Iterator iter = map.keySet().iterator();
        while(iter.hasNext()){
            System.out.println(map.get(iter.next()));
        }
    }
   
}

4.看测试结果
==================get测试=====================
Received response from: 192.168.0.100/161
1.3.6.1.2.1.1.1.0:Hardware: x86 Family 15 Model 2 Stepping 9 AT/AT COMPATIBLE - Software: Windows 2000 Version 5.1 (Build 2600 Uniprocessor Free)
==================getNext测试=================
共5个接口
MS TCP Loopback interface
VMware Virtual Ethernet Adapter for VMnet8
VMware Virtual Ethernet Adapter for VMnet1
Realtek RTL8139 Family PCI Fast Ethernet NIC - 数据包计划程序微型端口
ASUS 802.11b/g Wireless LAN Card - 数据包计划程序微型端口

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SNMP4J-Agent是一个Java实现的简单网络管理协议(Simple Network Management Protocol, SNMP)代理。它允许Java应用程序作为SNMP管理器或代理,参与到SNMP网络管理系统中。以下是使用SNMP4J-Agent的基本概念和操作: 1. **创建代理**: 在SNMP4J中,你需要创建一个`DefaultUdpTransportMapping`实例来设置网络监听地址[^4]。例如: ```java TransportMapping transport = new DefaultUdpTransportMapping(); transport.setDatagramSocketFactory(new UdpSocketFactoryImpl()); transport.listen(); ``` 2. **配置MIBs**: 为了处理特定的SNMP对象定义,你需要加载MIBs (Management Information Base)。这通常通过`MibBuilder`和`MibTree`完成[^5]: ```java MibBuilder mibBuilder = new MibBuilder(); mibBuilder.addRepository(new File("path/to/mibs")); MibTree mibTree = mibBuilder.getMibTree(); ``` 3. **设置社区字符串**: SNMP通信中使用社区字符串进行身份验证。你可以创建一个`CommunityTarget`来指定目标主机和社区字符串[^6]: ```java CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString("public")); target.setAddress(new InetAddress("localhost")); // 目标IP ``` 4. **执行GET/SET操作**: 使用`SnmpEngine`和`PDU`类执行SNMP GET或SET请求[^7]: ```java SnmpEngine snmpEngine = new SnmpEngine(); PDU request = new GetRequest(); request.addVarbind(new Varbind(new OID("1.3.6.1.2.1.1.1.0"))); // 操作对象ID PDU response = null; try { response = snmpEngine.send(request, target); } catch (SnmpException e) { // 处理异常 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值