snmp4j实现SNMPv1/2/3 开发(代码)

先贴上自己的代码,以后在讲解,很幼稚的设计思路,只是个雏形,可贵的是完成了SNMPv123的测试

只有一个Main类:

import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;

public class Main {

    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in);
        System.out.println("请设定snmp版本:");
        int version = input.nextInt();
        System.out.println("设定的snmp版本为:" + version);

       if (1==version||2==version){
           try {
               Main a = new Main();
               a.getRequest();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }else if (3==version){
           String nmsAdmin = "";
           String AuthKey="";
           String nmsPrivKey="";
           String ip ="";
           long timeout = 0;
           int retry = 0;

           Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
           USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
           SecurityModels.getInstance().addSecurityModel(usm);
           snmp.listen();

           // 实例化user,并设置属性
           Scanner set = new Scanner(System.in);

           System.out.println("请输入检测对象的IP:");
           ip = input.next();
           System.out.println("请输入用户名称:");
           nmsAdmin = set.next();
           System.out.println("请输入认证秘钥:");
           AuthKey = set.next();
           System.out.println("请输入加密秘钥");
           nmsPrivKey = set.next();
           System.out.println("请设定超时时间:");
           long timeout0 = input.nextInt();
           timeout = timeout0 * 1000L;
           System.out.println("设定的超时时间为:" + timeout0 + "秒");
           System.out.println("请设定重试次数:");
           retry = input.nextInt();

           UsmUser user = new UsmUser(
                   new OctetString(nmsAdmin),          // 安全名称
                   AuthMD5.ID,                                       // 认证协议
                   new OctetString(AuthKey),        // 认证秘钥
                   PrivDES.ID,                                       // 加密算法
                   new OctetString(nmsPrivKey));       // 加密密钥

           snmp.getUSM().addUser(new OctetString(nmsAdmin), user);

           // 构造发送目标,SNMPv 1/2,实例化一个CommunityTarget对象。如果是SNMPv3,则需要实例化一个UserTarget对象。
           UserTarget target = new UserTarget();
           // 设置target
           target.setVersion(SnmpConstants.version3);                                    // 设置版本
           target.setAddress(new UdpAddress(ip+"/161"));                           // 目的IP、端口号
           target.setTimeout(timeout);                                                      // 等待延时
           target.setRetries(retry);                                                         // 重试次数
           target.setSecurityLevel(SecurityLevel.AUTH_PRIV);                             // 安全级别-v3特有
           target.setSecurityName(new OctetString(nmsAdmin));              // 安全名称-v3特有

           OctetString contextEngineId = new OctetString("0002651100[02]");  // 初始化上下文引擎ID

           sendRequest(snmp, createGetPdu(contextEngineId), target);                     // 发送请求报文

           snmpWalk(snmp, target, contextEngineId);
       }

    }

    public void getRequest()throws IOException{
        String protocol = "udp";
        int port = 161;
        String ip ="";
        String community ="";
        long timeout = 0;
        int retry = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("请输入检测对象的IP:");
        ip = input.next();
        System.out.println("检测对象IP:" + ip);
        System.out.println("请输入community:");
        community = input.next();
        System.out.println("团体名:" + community);
        System.out.println("请设定超时时间:");
        long timeout0 = input.nextInt();
        timeout = timeout0 * 1000L;
        System.out.println("设定的超时时间为:" + timeout0 + "秒");
        System.out.println("请设定重试次数:");
        retry = input.nextInt();
        System.out.println("设定的重试次数为:" + retry + "次");
        System.out.println("选择要采集的对象:");
        String oid = input.next();
        //System.out.println("要采集的对象为:" + oid );

        //创建对象transport
        TransportMapping transport = new DefaultUdpTransportMapping();

        //创建并初始化对象snmpClient
        Snmp snmpClient = new Snmp(transport);
        transport.listen();

        //创建并初始化对象address
        Address address = GenericAddress.parse(protocol+":"+ip+"/"+port);

        //创建并初始化对象target
        Target target = new CommunityTarget(address,new OctetString(community));

        //对象调用方法,来设置SNMP版本-version2c、尝试次数、超时时间
        target.setVersion(SnmpConstants.version2c);
        target.setRetries(retry);
        target.setTimeout(timeout);

        //创建对象request
        PDU request = new PDU();

        //设置类型-GET
        request.setType(PDU.GET);

        //添加OID
        request.add(new VariableBinding(new OID(oid)));

        //创建并初始化对象:响应事件
        ResponseEvent respEvent = snmpClient.send(request,target);

        //创建对象response接收响应
        PDU response = respEvent.getResponse();

        if (null!=response){
            if (response.size()>0){
                    //创建对象变量,来接收响应结果
                    VariableBinding vbi = response.get(0);
                    System.out.println("采集结果为:"+vbi.getVariable().toString());

            }
        }
    }

    private static PDU createGetPdu(OctetString contextEngineId) {

        ScopedPDU pdu = new ScopedPDU();            // 构造pdu
        pdu.setType(PDU.GET);                       // 设置请求类型
        pdu.setContextEngineID(contextEngineId);	// 如果不设置, 将会是SNMP引擎ID
        //pdu.setContextName(contextName);          // 设置上下文名称,必须和代理的一样

        //设置OID,即要访问的对象
        pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.0")));	// sysUpTime
        pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0")));	// sysName
        pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5")));	// expect an no_such_instance error
        return pdu;
    }

    /*
     * 同步模式发送消息后便等待响应的到达,到达之后会返回一个ResponseEvent对象,该对象中包含了响应的相应信息。
     * 异步模式发送消息之后便会继续执行,当收到响应消息时便会调用监听对象的OnResponse函数。
     */
    private static void sendRequest(Snmp snmp, PDU pdu, UserTarget target)
            throws IOException {
        ResponseEvent responseEvent = snmp.send(pdu, target);   // 将pdu发送给target,返回一个response
        PDU response = responseEvent.getResponse();             // 返回的response

        if (response == null) {                                 // 如果response为空
            System.out.println("TimeOut...");

        } else {                                                // 如果response不为空

            if (response.getErrorStatus() == PDU.noError) {
                Vector<? extends VariableBinding> vbs = response.getVariableBindings();
                for (VariableBinding vb : vbs) {
                    System.out.println(vb + " ," + vb.getVariable().getSyntaxString());
                }
            } else {
                System.out.println("Error:" + response.getErrorStatusText());
            }
        }
    }

    private static void snmpWalk(Snmp snmp, UserTarget target, OctetString contextEngineId) {

        TableUtils utils = new TableUtils(snmp,
                new MyDefaultPDUFactory(PDU.GETNEXT, //GETNEXT or GETBULK)
                        contextEngineId));
        utils.setMaxNumRowsPerPDU(5);	//only for GETBULK, set max-repetitions, default is 10
        OID[] columnOids = new OID[] {
                new OID("1.3.6.1.2.1.1.9.1.2"),	//sysORID
                new OID("1.3.6.1.2.1.1.9.1.3")	//sysORDescr
        };
        // If not null, all returned rows have an index in a range (lowerBoundIndex, upperBoundIndex]
        List<TableEvent> l = utils.getTable(target, columnOids, new OID("3"), new OID("10"));
        for (TableEvent e : l) {

            System.err.println(e);

        }
    }

    private static class MyDefaultPDUFactory extends DefaultPDUFactory {
        private OctetString contextEngineId = null;
        public MyDefaultPDUFactory(int pduType, OctetString contextEngineId) {
            super(pduType);
            this.contextEngineId = contextEngineId;
        }

        @Override
        public PDU createPDU(Target target) {
            PDU pdu = super.createPDU(target);
            if (target.getVersion() == SnmpConstants.version3) {
                ((ScopedPDU) pdu).setContextEngineID(contextEngineId);
            }
            return pdu;
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_28657577/article/details/82350914