SNMP v1 v2c v3配置以及java端如何使用snmp4j

此次配置基于CentOS7.x

一,Linux配置:

1、检测是否有 SNMP 服务

service snmpd status

  

2、若没有则安装

yum install -y net-snmp

  

3、编辑 SNMP 的配置文件,设置安全的验证方式

      修改配置文件之前,请先停止服务

systemctl stop snmpd.service 
vim /etc/snmp/snmpd.conf 

   验证方式有两种: v2c、v3,下文分别介绍 

      3.1  v1,v2c的配置方式:

            1,将原有snmpd.conf配置文件做备份,备份名字是snmpd.conf.bak(可以随意起)

            2,创建一个空的snpmd.conf配置文件,并进入 vim /etc/snmp/snmpd.conf

            3,在空的配置文件中写入配置,其中:snmp_pwd为团体名(起自己喜欢的名字),其他配置不变 如下:

com2sec notConfigUser default snmp_pwd
group notConfigGroup v1 notConfigUser
group notConfigGroup v2c notConfigUser
access notConfigGroup "" any noauth exact all none none
view all included .1 
view mib2 included .iso.org.dod.internet.mgmt.mib-2 fc
dontLogTCPWrappersConnects yes

       3.2  v3的配置方式:

              使用命令创建V3用户:

net-snmp-create-v3-user

    之后输入用户名:snmpv3user

    输入认证密码:auth-password

    输入加密密码:encrypt-password

    如图:

    

    其中:

    snmpv3user 是SNMPv3用户 --可以用户自定义名称

    auth-password 作为认证密码 --可以用户自定义名称

    encrypt-password 作为加密密码 --可以用户自定义名称

    注:v1 v2c v3的配置可以同时配置

    启动服务:

systemctl start snmpd.service

    查看状态:

service snmpd status

    v3测试:

snmpwalk -v 3 -u snmpv3user -a MD5 -A auth-password -l authPriv -x DES -X encrypt-password localhost

    可以看到我们顺利的取到了服务器的snmp数据。

   

4、SNMPWALK未找到命令的解决办法

  安装 net-snmp-perl net-snmp-utils 即可

yum install -y net-snmp-perl net-snmp-utils

5,配置防火墙,开启端口

      如果服务器需要启动防火墙则做如下配置,如果不启动防火墙则不需要

      查看firewalld状态,发现当前是dead状态,即防火墙未开启。

systemctl status firewalld

      开启防火墙命令

systemctl start firewalld

      关闭防火墙命令

systemctl stop firewalld

      查看已开放的端口(默认不开放任何端口)

firewall-cmd --list-ports

     开启 161 端口

firewall-cmd --zone=public --add-port=161/udp --permanent

      重启防火墙

firewall-cmd --reload

      防火墙常用命令(上一步结束后,不需要执行以下防火墙步骤):

      停止防火墙

systemctl stop firewalld.service

      禁止防火墙开机启动

systemctl disable firewalld.service

     删除161端口命令

firewall-cmd --permanent --zone=public --remove-port=161/udp

6,常用命令总结

   查询SNMP服务:

service snmpd status

   启动SNMP服务:

systemctl start snmpd.service

   关闭SNMP服务:

systemctl stop snmpd.service 

  重启SNMP服务:

systemctl restart snmpd.service

  开机启动SNMP服务:

chkconfig snmpd on

  关闭开机启动SNMP服务:

chkconfig snmpd off

二,Java调用SNMP服务代码--snmp4j

1,pom.xml中引入snmp4j的依赖

<dependency>
    <groupId>org.snmp4j</groupId>
    <artifactId>snmp4j</artifactId>
    <version>2.5.11</version>
</dependency>

2,编写snmpV2c工具类,适用于v1(修改版本号即可)

package com.example.demo.test.snmp.test.snmpV2;

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;

/**
 * SNMP V2 工具类
 */
public class SnmpV2cUtil {

  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 ip
   * @param community
   * @return
   */
  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;
  }

  /**
   * GET 方式获取信息
   *
   * @param ip
   * @param community
   * @param oid
   */
  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;
        }
      }
    }
  }

  /**
   * GET 方式批量获取信息
   *
   * @param ip
   * @param community
   * @param oidList
   */
  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;
        }
      }
    }
  }

  /**
   * GET方式异步获取信息
   *
   * @param ip
   * @param community
   * @param oidList
   */
  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;
        }
      }
    }
  }

  /**
   * WALK 方式获取信息
   *
   * @param ip
   * @param community
   * @param targetOid
   */
  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;
        }
      }
    }
  }

  /**
   * WALK方式 异步获取信息
   * @param ip
   * @param community
   * @param oid
   */
  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);
    }
  }

  /**
   * WALK检查方法
   * @param targetOID
   * @param pdu
   * @param vb
   * @return
   */
  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 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 com.example.demo.test.snmp.test.snmpV2;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;


public class SnmpV2cTest {

  /**
   * 测试GET方式取值
   */
  @Test
  public void testGet() {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    String oidval = "1.3.6.1.4.1.2021.11.11.0";
    SnmpV2cUtil.snmpGet(ip, community, oidval);
  }

  /**
   * 测试批量GET方式取值
   */
  @Test
  public void testGetList() {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    List<String> oidList = new ArrayList<String>();
    oidList.add("1.3.6.1.2.1.1.4.0");
    oidList.add("1.3.6.1.2.1.1.5.0");
    SnmpV2cUtil.snmpGetList(ip, community, oidList);
  }

  /**
   * 测试批量GET方式异步取值
   */
  @Test
  public void testGetAsyList() {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    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.4.0");
    SnmpV2cUtil.snmpAsynGetList(ip, community, oidList);

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

  /**
   * 测试WALK方式取值
   */
  @Test
  public void testWalk() {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    String targetOid = "1.3.6.1.2.1.25.2.3.1.5";
    SnmpV2cUtil.snmpWalk(ip, community, targetOid);
  }

  /**
   * 测试WALK异步方式取值
   */
  @Test
  public void testAsyWalk() {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    // 异步采集数据
    SnmpV2cUtil.snmpAsynWalk(ip, community, "1.3.6.1.2.1.25.4.2.1.2");
  }

  /**
   * 测试设置pdu
   * @throws Exception
   */
  @Test
  public void testSetPDU() throws Exception {
    String ip = "192.168.2.2";
    String community = "snmp_pwd";
    SnmpV2cUtil.setPDU(ip, community, "1.3.6.1.2.1.1.6.0");
  }

}

3,编写SNMP V3工具类

创建常量类:

package com.example.demo.test.snmp.test.constant;

import org.snmp4j.mp.SnmpConstants;

/**
 * v3常量类
 */
public class SnmpCon {

  //snmp版本
  public static final int DEFAULT_VERSION_V3 = SnmpConstants.version3;
  //udp
  public static final String DEFAULT_PROTOCOL = "udp";
  //被访问设备的IP地址
  public static final String IP_ADDRESS = "192.168.2.2/";
  //端口号
  public static final String DEFAULT_PORT = "161";
  //团体名
  public static final String COMMUNITY = "snmp_pwd";
  //v3用户名 -配置SNMP v3时 手动设置 写自己定义的名字
  public static final String USM_USER = "snmpv3user";
  //authMD5-加密,配置SNMP v3时 手动设置的 写自己定义的密码
  public static final String AUTH_MD5 = "auth-password";
  //PIRV_DES-加密,配置SNMP v3时 手动设置的 写自己定义的密码
  public static final String PREV_DES = "encrypt-password";
  //超时时间
  public static final long DEFAULT_TIMEOUT = 3 * 1000L;
  //重置
  public static final int DEFAULT_RETRY = 0;
}

创建工具类:

package com.example.demo.test.snmp.test.snmpV3;

import com.example.demo.test.snmp.test.constant.SnmpCon;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.event.ResponseListener;
import org.snmp4j.mp.MPv3;
import org.snmp4j.security.AuthMD5;
import org.snmp4j.security.PrivDES;
import org.snmp4j.security.SecurityLevel;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
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;


public class SnmpV3Util {

  /**
   * 创建对象UserTarget
   *
   * @return
   */
  public static UserTarget createDefault() {
    //如果有问题可能是address的问题 v3没有udp--现在是加上udp测试的
    Address address = GenericAddress
        .parse(SnmpCon.DEFAULT_PROTOCOL + ":" + SnmpCon.IP_ADDRESS
            + "/" + SnmpCon.DEFAULT_PORT);
    UserTarget target = new UserTarget();
    target.setVersion(SnmpCon.DEFAULT_VERSION_V3);
    target.setAddress(address);
    target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
    target.setSecurityName(new OctetString(SnmpCon.USM_USER));
    target.setTimeout(SnmpCon.DEFAULT_TIMEOUT);
    target.setRetries(SnmpCon.DEFAULT_RETRY);
    return target;
  }

  /**
   * snmpV3Get方式获取数据
   *
   * @param oid 设备OID
   */
  public static void snmpV3Get(String oid) {
    UserTarget target = createDefault();
    Snmp snmp = null;
    try {
      ScopedPDU pdu = new ScopedPDU();
      pdu.setType(PDU.GET);
      pdu.setContextEngineID(new OctetString(SnmpCon.COMMUNITY));
      pdu.add(new VariableBinding(new OID(oid)));
      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      USM usm = new USM(SecurityProtocols.getInstance(),
          new OctetString(MPv3.createLocalEngineID()),
          0);
      SecurityModels.getInstance().addSecurityModel(usm);
      snmp.listen();
      //验证密码
      UsmUser user = new UsmUser(new OctetString(SnmpCon.USM_USER), AuthMD5.ID,
          new OctetString(SnmpCon.AUTH_MD5), PrivDES.ID, new OctetString(SnmpCon.PREV_DES));
      snmp.getUSM().addUser(new OctetString(SnmpCon.USM_USER), user);

      System.out.println("-------> 发送PDU <-------");
      ResponseEvent respEvent = snmp.send(pdu, target);
      System.out.println("被访问设备的IP地址及端口号:  " + respEvent.getPeerAddress());
      PDU response = respEvent.getResponse();
      if (response == null) {
        System.out.println("response is null, request time out");
      } else {
        if (response.getErrorStatus() == PDU.noError) {
          Vector<? extends VariableBinding> vbs = response.getVariableBindings();
          for (VariableBinding vb : vbs) {
            System.out.println("****** 返回结果 ******");
            System.out.println(vb + " ," + vb.getVariable().getSyntaxString());
            System.out.println("************");
          }
        } else {
          System.out.println("Error:" + response.getErrorStatusText());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (snmp != null) {
        try {
          snmp.close();
        } catch (IOException ex1) {
          snmp = null;
        }
      }
    }
  }


  /**
   * snmp v3 批量获取设备信息
   *
   * @param oidList
   */
  public static void snmpV3GetList(List<String> oidList) {
    UserTarget target = createDefault();
    Snmp snmp = null;
    try {
      ScopedPDU pdu = new ScopedPDU();
      pdu.setType(PDU.GET);
      pdu.setContextEngineID(new OctetString(SnmpCon.COMMUNITY));
      for (String oid : oidList) {
        pdu.add(new VariableBinding(new OID(oid)));
      }
      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      USM usm = new USM(SecurityProtocols.getInstance(),
          new OctetString(MPv3.createLocalEngineID()),
          0);
      SecurityModels.getInstance().addSecurityModel(usm);
      snmp.listen();

      UsmUser user = new UsmUser(new OctetString(SnmpCon.USM_USER), AuthMD5.ID,
          new OctetString(SnmpCon.AUTH_MD5), PrivDES.ID, new OctetString(SnmpCon.PREV_DES));
      snmp.getUSM().addUser(new OctetString(SnmpCon.USM_USER), user);

      System.out.println("-------> 发送PDU <-------");
      ResponseEvent respEvent = snmp.send(pdu, target);
      System.out.println("被访问设备的IP地址及端口号:  " + respEvent.getPeerAddress());
      PDU response = respEvent.getResponse();
      if (response == null) {
        System.out.println("response is null, request time out");
      } else {
        if (response.getErrorStatus() == PDU.noError) {
          Vector<? extends VariableBinding> vbs = response.getVariableBindings();
          for (VariableBinding vb : vbs) {
            System.out.println("****** 返回结果 ******");
            System.out.println(vb + " ," + vb.getVariable().getSyntaxString());
            System.out.println("************");
          }
        } else {
          System.out.println("Error:" + response.getErrorStatusText());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (snmp != null) {
        try {
          snmp.close();
        } catch (IOException ex1) {
          snmp = null;
        }
      }
    }
  }


  /**
   * snmp v3 异步批量获取设备信息
   *
   * @param oidList
   */
  public static void snmpV3AsynGetList(List<String> oidList) {
    UserTarget target = createDefault();
    Snmp snmp = null;
    try {
      ScopedPDU pdu = new ScopedPDU();
      pdu.setType(PDU.GET);
      pdu.setContextEngineID(new OctetString(SnmpCon.COMMUNITY));
      for (String oid : oidList) {
        pdu.add(new VariableBinding(new OID(oid)));
      }
      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      USM usm = new USM(SecurityProtocols.getInstance(),
          new OctetString(MPv3.createLocalEngineID()),
          0);
      SecurityModels.getInstance().addSecurityModel(usm);
      snmp.listen();

      UsmUser user = new UsmUser(new OctetString(SnmpCon.USM_USER), AuthMD5.ID,
          new OctetString(SnmpCon.AUTH_MD5), PrivDES.ID, new OctetString(SnmpCon.PREV_DES));
      snmp.getUSM().addUser(new OctetString(SnmpCon.USM_USER), user);

      System.out.println("-------> 发送PDU <-------");
      ResponseEvent respEvent = snmp.send(pdu, target);
      System.out.println("被访问设备的IP地址及端口号:  " + respEvent.getPeerAddress());

      /*异步获取*/
      final CountDownLatch latch = new CountDownLatch(oidList.size());
      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("response is null, request time out");
          } else {
            if (response.getErrorStatus() == PDU.noError) {
              Vector<? extends VariableBinding> vbs = response.getVariableBindings();
              for (VariableBinding vb : vbs) {
                System.out.println("****** 返回结果 ******");
                System.out.println(vb + " ," + vb.getVariable().getSyntaxString());
                System.out.println("************");
              }
            } else {
              System.out.println("Error:" + response.getErrorStatusText());
            }
            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;
        }
      }
    }
  }

  /**
   * SNMP V3 WALK 方式获取数据
   *
   * @param oid
   */
  public static void snmpV3Walk(String oid) {
    UserTarget target = createDefault();
    Snmp snmp = null;
    try {
      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      USM usm = new USM(SecurityProtocols.getInstance(),
          new OctetString(MPv3.createLocalEngineID()),
          0);
      SecurityModels.getInstance().addSecurityModel(usm);
      snmp.listen();
      UsmUser user = new UsmUser(new OctetString(SnmpCon.USM_USER), AuthMD5.ID,
          new OctetString(SnmpCon.AUTH_MD5), PrivDES.ID, new OctetString(SnmpCon.PREV_DES));
      snmp.getUSM().addUser(new OctetString(SnmpCon.USM_USER), user);
      ScopedPDU pdu = new ScopedPDU();
      OID targetOID = new OID(oid);
      pdu.add(new VariableBinding(targetOID));
      boolean finished = false;
      System.out.println("-------> 发送PDU <-------");
      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("-------> 发送PDU结束 <-------");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("SNMP walk Exception: " + e);
    } finally {
      if (snmp != null) {
        try {
          snmp.close();
        } catch (IOException ex1) {
          snmp = null;
        }
      }
    }
  }

  /**
   * WALK 方式 异步获取数据
   *
   * @param oid
   */
  public static void snmpV3AsynWalk(String oid) {
    UserTarget target = createDefault();
    Snmp snmp = null;
    try {
      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      snmp = new Snmp(transport);
      USM usm = new USM(SecurityProtocols.getInstance(),
          new OctetString(MPv3.createLocalEngineID()),
          0);
      SecurityModels.getInstance().addSecurityModel(usm);
      snmp.listen();
      UsmUser user = new UsmUser(new OctetString(SnmpCon.USM_USER), AuthMD5.ID,
          new OctetString(SnmpCon.AUTH_MD5), PrivDES.ID, new OctetString(SnmpCon.PREV_DES));
      snmp.getUSM().addUser(new OctetString(SnmpCon.USM_USER), user);
      ScopedPDU pdu = new ScopedPDU();
      OID targetOID = new OID(oid);
      pdu.add(new VariableBinding(targetOID));
      final CountDownLatch latch = new CountDownLatch(1);
      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("-------> 发送PDU结束 <-------");

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("SNMP Asyn Walk Exception:" + e);
    }
  }

  /**
   * 检查WALK
   *
   * @param targetOID
   * @param pdu
   * @param vb
   * @return
   */
  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;
  }
}

测试类:

package com.example.demo.test.snmp.test.snmpV3;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

public class SnmpV3Test {

  /**
   * 测试v3 GET 方式获取
   */
  @Test
  public void snmpV3Get() {
    String oid = "1.3.6.1.2.1.25.2.2.0";
    SnmpV3Util.snmpV3Get(oid);
  }

  /**
   * 测试v3 GET 方式批量获取
   */
  @Test
  public void snmpV3GetList() {
    List<String> oidList = new ArrayList<String>();
    oidList.add("1.3.6.1.2.1.1.1.0");
    oidList.add("1.3.6.1.2.1.1.3.0");
    oidList.add("1.3.6.1.2.1.1.4.0");
    SnmpV3Util.snmpV3GetList(oidList);
  }

  /**
   * 测试v3 GET 方式异步批量获取
   */
  @Test
  public void snmpV3AsynGetList() {
    List<String> oidList = new ArrayList<String>();
    oidList.add("1.3.6.1.2.1.1.1.0");
    oidList.add("1.3.6.1.2.1.1.3.0");
    oidList.add("1.3.6.1.2.1.1.4.0");
    SnmpV3Util.snmpV3AsynGetList(oidList);
  }

  /**
   * 测试v3 WALK 方式获取数据
   */
  @Test
  public void snmpV3Walk() {
    String oid = "1.3.6.1.2.1.25.2.3.1.5";
    SnmpV3Util.snmpV3Walk(oid);
  }


  /**
   * 测试v3 WALK 异步方式获取数据
   */
  @Test
  public void snmpV3AsynWalk() {
    String oid = "1.3.6.1.2.1.25.2.3.1.5";
    SnmpV3Util.snmpV3AsynWalk(oid);
  }

}

 

 

 

 

 

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值