snmp工具类

 

 依赖


			org.snmp4j
			snmp4j
			2.5.11
package com.ireal.crpas.test.SnmpAbout;

import com.ireal.crpas.protocol.model.Result;
import com.ireal.crpas.test.SnmpAbout.model.MonitorBaseInfo;
import com.ireal.crpas.test.SnmpAbout.model.ResultRes;
import com.ireal.crpas.test.SnmpAbout.utils.snmpXmlUtils;
import org.apache.commons.lang3.StringUtils;
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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class Snmp_api implements Snmp_aip_interface {
    private Snmp snmp;
    private TransportMapping transportMapping;
    private int timeOut;
    private int timesRetry;
    public Snmp_api(){
//        Thread thread_rec = new receiveTrapThread();
//        thread_rec.start();
//        listen();
    }

    private void init(){
        try {
            transportMapping = new DefaultUdpTransportMapping();


        } catch (IOException e) {
            System.out.println("init transportMapping failed!");
            System.out.println(e.getMessage());
        }
        snmp = new Snmp(transportMapping);
        timeOut = 1500;
        timesRetry = 2;
    }

    /**
     * 根据ip,oid返回get消息
     * @param ip
     * @param oid_str
     * @return
     */
    public String get(String ip, String oid_str){
        init();
        String ret = "";
        //构造PDU
        PDU pdu = new PDU();
        OID oid = new OID(oid_str);
        VariableBinding vb = new VariableBinding(oid);
        pdu.add(vb);
        pdu.setType(PDU.GET);

        //构造target
        String address_str = "udp:" + ip + "/161";
//        String address_str = "udp:210.38.235.184/161";
        Address address = GenericAddress.parse(address_str);
        OctetString name_com = new OctetString("public");
        CommunityTarget target = new CommunityTarget();
        target.setAddress(address);                                        //设置address
        target.setRetries(timesRetry);
        target.setTimeout(timeOut);
        target.setVersion(SnmpConstants.version2c);                        //设置版本号
        target.setCommunity(name_com);                                    //设置团体名

        try {
            this.transportMapping.listen();
        } catch (IOException e) {
            System.out.println("transportMapping.listen() failed!");
            System.out.println(e.getMessage());
        }
        ResponseEvent responseEvent = null;
        //发送消息
        try {
            responseEvent = snmp.send(pdu, target);
        } catch (IOException e) {
            System.out.println("snmp.send(pdu, target) failed");
            System.out.println(e.getMessage());
        }
        //获取结果
        if(responseEvent != null){
            PDU pdu_rep = responseEvent.getResponse();
            for(int i = 0; i < pdu_rep.size(); i++){
                VariableBinding vb_temp = pdu_rep.get(i);
                Variable var_temp = vb_temp.getVariable();
                ret += var_temp.toString();
               // ret += vb_temp.getOid();
            }//for
        }//if
        try {
            transportMapping.close();                                    //关闭正在进行的监听
        } catch (IOException e) {
            System.out.println("transportMapping.close() failed!");
            System.out.println(e.getMessage());
        }
        return ret;
    }


    /**
     * 根据ip,oid和新值设置oid节点的值
     * @param ip
     * @param oid_str
     * @param value_new
     */
    public void set(String ip, String oid_str, String value_new){
        init();
        //构造PDU
        PDU pdu = new PDU();
        OID oid = new OID(oid_str);
        VariableBinding vb = null;

        vb = new VariableBinding(oid, new OctetString(value_new));

        pdu.add(vb);
        pdu.setType(PDU.SET);

        //构造target
        String address_str = "udp:" + ip + "/161";
        CommunityTarget target = new CommunityTarget();
        OctetString com_oct = new OctetString("public");
        target.setCommunity(com_oct);                                    //设置团体名
        Address address = GenericAddress.parse(address_str);
        target.setAddress(address);                                        //设置address
        target.setVersion(SnmpConstants.version2c);                     //设置版本号
        target.setTimeout(1500);
        target.setRetries(timesRetry);

        //发送pdu
        try {
            transportMapping.listen();
        } catch (IOException e) {
            System.out.println("listen failed in set pdu");
            System.out.println(e.getMessage());
        }
        try {
            snmp.send(pdu, target);
        } catch (IOException e) {
            System.out.println("send failed in send set message!");
            System.out.println(e.getMessage());
        } finally{
            try {
                transportMapping.close();                                //关闭正在进行的监听
            } catch (IOException e) {
                System.out.println("transportMapping.close() failed!");
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 根据ip,oid返回getNext消息
     * @param ip
     * @param oid_str
     * @return
     */
    public String getNext(String ip, String oid_str){
        init();
        String ret = "";
        //构造PDU
        PDU pdu = new PDU();
        OID oid = new OID(oid_str);
        VariableBinding vb = new VariableBinding(oid);
        pdu.add(vb);
        pdu.setType(PDU.GETNEXT);

        //构造target
        String address_str = "udp:" + ip + "/161";                                    //UDP和ip
        CommunityTarget target = new CommunityTarget();
        Address address = GenericAddress.parse(address_str);
        target.setCommunity(new OctetString("public"));
        target.setAddress(address);
        target.setTimeout(timeOut);
        target.setRetries(timesRetry);
        target.setVersion(SnmpConstants.version2c);                                 //设置版本号

        ResponseEvent responseEvent = null;

        try {
            this.transportMapping.listen();                                            //开始监听
        } catch (IOException e1) {
            System.out.println("transportMapping.listen() failed!");
            System.out.println(e1.getMessage());
        }

        //发送消息
        try {
            responseEvent = snmp.send(pdu, target);
            if(responseEvent != null){                                                //组装返回的消息
                PDU pdu_reponse = responseEvent.getResponse();
                for(int i = 0; pdu_reponse != null && i < pdu_reponse.size(); i++){
                    VariableBinding vb_temp = pdu_reponse.get(i);
                    Variable var_temp = vb_temp.getVariable();
                    ret += var_temp.toString();
                }
            }
        } catch (IOException e) {
            System.out.println("snmp.send(pdu, target) failed! in getNext");
            e.printStackTrace();
        } finally{                                                                    //关闭监听
            try {
                this.transportMapping.close();
                snmp.close();
            } catch (IOException e) {
                System.out.println("transportMapping.close() failed!");
                System.out.println(e.getMessage());
            }
        }//finally

        return ret;
    }

    /**
     * 根据ip,oid获取bulk消息
     * @param ip
     * @param oid_str
     * @return
     */
    public List getBulk(String ip, String oid_str){
        init();
        List ret = new ArrayList();
        //构造PDU
        PDU pdu = new PDU();
        pdu.setType(PDU.GETBULK);
        pdu.setMaxRepetitions(200);
        pdu.setNonRepeaters(0);
        OID oid = new OID(oid_str);
        VariableBinding vb = new VariableBinding(oid);
        pdu.add(vb);

        //构造target
        String address_str = "udp:" + ip + "/161";                                    //UDP和ip
        CommunityTarget target = new CommunityTarget();
        Address address = GenericAddress.parse(address_str);
        target.setCommunity(new OctetString("public"));
        target.setVersion(SnmpConstants.version2c);
        target.setAddress(address);
        target.setTimeout(timeOut);
        target.setRetries(timesRetry);

        try {                                                                        //开始监听UDP端口
            this.transportMapping.listen();
        } catch (IOException e) {
            System.out.println("transportMapping.listen() failed!");
            System.out.println(e.getMessage());
        }

        //发送消息
        ResponseEvent responseEvent = null;
        try {
            responseEvent = this.snmp.send(pdu, target);
        } catch (IOException e) {
            System.out.println(".snmp.send(pdu, target) failed! in getBulk");
            e.printStackTrace();
        }

        if(responseEvent.getResponse() != null){
            PDU pdu_rec = responseEvent.getResponse();

            System.out.println(pdu_rec.size());                                            //输出为0,说明前面没有获取到数据
            for(int i = 0; i < pdu_rec.size(); i++){
                String str_temp = "";
                VariableBinding vb_temp = pdu_rec.get(i);
                str_temp += vb_temp.getOid() + "-";
                str_temp += vb_temp.getVariable().toString();
                ret.add(str_temp);
            }//for
        }//if

        try {
            this.transportMapping.close();
        } catch (IOException e) {
            System.out.println("transportMapping.close() failed!");
            System.out.println(e.getMessage());
        }
        return ret;
    }

    /**
     * 接收trap消息线程
     * @author Administrator
     *
     */
    private class receiveTrapThread extends Thread{
        public void run(){
            System.out.println("start run thread..");

            try {
                transportMapping.listen();
            } catch (IOException e) {
                System.out.println("listen failed in receiveTrapThread.run()!");
                e.printStackTrace();
            }
            CommandResponder commandResponder = new CommandResponder(){
                @Override
                public void processPdu(CommandResponderEvent event) {
                    System.out.println("enter processPdu()...");
                    PDU pdu_receive = event.getPDU();
                    StringBuffer sb = new StringBuffer();

                    for(int i = 0; i < pdu_receive.size(); i++){
                        VariableBinding vb_temp = pdu_receive.get(i);
                        sb.append(vb_temp.getVariable().toString());
                    }//for
                    System.out.println(sb.toString());
                }

            };
            snmp.addCommandResponder(commandResponder);
        }
    }

    public synchronized void listen(){
        System.out.println("start listen..");
        try {
            this.wait();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }


    /* (non-Javadoc)
     * @see com.gxf.snmp.interfaces.Snmp_aip_interface#getV3(java.lang.String, java.lang.String)
     */
    @Override
    public String getV3(String ip, String oid_str) {
        Snmp snmp = null;
        try {
            snmp = new Snmp(new DefaultUdpTransportMapping());

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

            snmp.listen();
        } catch (IOException e) {
            e.printStackTrace();
        }
        UsmUser user = new UsmUser(
                new OctetString("luckygxf"),
                AuthMD5.ID, new OctetString("luckygxf"),
                PrivDES.ID, new OctetString("luckygxf")
        );
        OctetString contextEngineId = new OctetString("0002651100[02]");
        snmp.getUSM().addUser(new OctetString("nmsAdmin"), new OctetString("0002651100"), user);
        snmp.getUSM().addUser(new OctetString("luckygxf"), user);
        String address_str = ip + "/161";
//        System.out.println("address_str = " + address_str);
        Address address = new UdpAddress(address_str);
        UserTarget target = new UserTarget();
        target.setVersion(SnmpConstants.version3);
        target.setAddress(address);
        target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
        target.setSecurityName(new OctetString("luckygxf"));
        target.setTimeout(2000);
        target.setRetries(1);

        ScopedPDU pdu = new ScopedPDU();
        pdu.setType(PDU.GET);
        pdu.setContextEngineID(contextEngineId);
        VariableBinding vb = new VariableBinding(new OID(oid_str));
        pdu.add(vb);

        ResponseEvent responseEvent = null;
        try {
            responseEvent = snmp.send(pdu, target);
        } catch (IOException e) {

            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();                        //返回的字符串
        if(null != responseEvent){
            PDU pdu_rec = responseEvent.getResponse();
//            System.out.println("pdu_rec.size() = " + pdu_rec.size());
            if(pdu_rec != null){
                Vector vbs = pdu_rec.getVariableBindings();
                for(VariableBinding vb_temp : vbs){
                    sb.append(vb_temp.getVariable().toString());
                }//for
            }
        }//if

        try {
            snmp.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    /* (non-Javadoc)
     * @see com.gxf.snmp.interfaces.Snmp_aip_interface#sendMessage(java.lang.String, java.lang.String)
     */
    @Override
    public void sendMessage(String ip, String message) {
        //构造trap PDU
        PDU pdu = new PDU();
        VariableBinding vb = new VariableBinding(new OID("1.3.6.1.2.3377.10.1.1.1.1"), new OctetString(message));
        pdu.add(vb);
        pdu.setType(PDU.TRAP);

        //构造target
        String address_str = "udp:" + ip + "/16200";                            //这里发送端口为16200
        CommunityTarget target = new CommunityTarget();
        Address address = GenericAddress.parse(address_str);
        target.setAddress(address);
        target.setVersion(SnmpConstants.version2c);
        target.setCommunity(new OctetString("public"));
        target.setTimeout(2000);
        target.setRetries(2);
        TransportMapping tranportMapping = null;
        try {
            tranportMapping = new DefaultUdpTransportMapping();
            tranportMapping.listen();
        } catch (IOException e) {
            System.out.println("sendTrap(String ip) failed in Snmp_api.sendTrap(String ip)!");
            e.printStackTrace();
        }
        Snmp snmp = new Snmp(tranportMapping);
        try {
            ResponseEvent responseEvent = snmp.send(pdu, target);                //得到回复的pdu
            if(null != responseEvent){
                StringBuffer sb = new StringBuffer();
                PDU pdu_rec = responseEvent.getResponse();
                for(int i = 0;pdu_rec != null && i < pdu_rec.size(); i++){
                    VariableBinding vb_temp = pdu_rec.get(i);
                    sb.append(vb.getVariable().toInt());
                }//for

                System.out.println(sb.toString());
            }
        } catch (IOException e) {
            System.out.println("snmp.send(pdu, target) failed in Snmp_api.sendTrap(String ip)!");
        }

        try {
            tranportMapping.close();
            snmp.close();                                                                        //关闭tansportmapping and snmp 释放资源
        } catch (IOException e) {
            System.out.println("tranportMapping.close() and snmp.close() failed in Snmp_api.sendTrap(String ip)!");
            e.printStackTrace();
        }

    }
    public List walkByTable(String oid, String ip){
        //initSnmp(snmpModel);
        PDU pdu;
        List result = new ArrayList();

        try {
            //4.1 初始化一般情况下,我们都使用使用UDP协议作为SNMP的传输层协议,所以我们需要实例化的是一个DefaultUdpTransportMapping接口对象;
            DefaultUdpTransportMapping dm = new DefaultUdpTransportMapping();

//			dm.setSocketTimeout(5000);
            // 在此过程中,我们需要将1中实例化的DefaultUdpTransportMapping接口的对象作为参数,穿snmp类的构造函数中。
            //  另外,如果实现的SNMPv3协议,我们还需要设置安全机制,添加安全用户等等
            snmp = new Snmp(dm);
            // 在此,我们可以调用刚刚实例化的DefaultUdpTransportMapping的接口对象的listen方法,让程序监听snmp消息;
            snmp.listen();
            //  4.2构造发送目标 如果实现的是SNMPv2c或者说SNMPv1,需要实例化一个CommunityTarget对象
            String address_str = "udp:" + ip + "/161";                                    //UDP和ip
            CommunityTarget target = new CommunityTarget();
            Address address = GenericAddress.parse(address_str);
            target.setCommunity(new OctetString("public"));
            target.setVersion(SnmpConstants.version2c);
            target.setAddress(address);
            target.setTimeout(timeOut);
            target.setRetries(timesRetry);

//           4.3 构建发送报文 如果发送的是SNMPv2c或者说SNMPv1的报文,我们需要实例化一个PDU类的对象。
//            之后,我们还需要生成一个OID对象,其中包含了我们所需要获取的SNMP对象在MIB库中的ID。
//            然后我们需要将OID和之前生成的PDU对象或者是ScopedPDU对象绑定,并且设置PDU的报文类型(五种SNMP报文类型之一)。
            DefaultPDUFactory defaultPDUFactory = new DefaultPDUFactory();
            defaultPDUFactory.setPduType(PDU.GETBULK);
            TableUtils tutils = new TableUtils(snmp, defaultPDUFactory);
            OID[] columns = new OID[1];
            columns[0] = new VariableBinding(new OID(oid)).getOid();
            List list = (List) tutils.getTable(target, columns, new OID("0"), new OID("50"));
            for(TableEvent e : list){
                VariableBinding[] vb = e.getColumns();
                if(null == vb)continue;
                result.add(vb[0].getVariable().toString());
//				 System.out.println(vb[0].getVariable().toString());
            }
            snmp.close();
        } catch (IOException e) {
            //e.printStackTrace();
            System.out.println(e.getMessage());
        }finally{
            try {
                if(snmp != null)
                {
                    snmp.close();
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        return result;

    }

    public List getMonitorBaseInfo (String Ip,String path) throws Exception {
        List getlistfromxml = snmpXmlUtils.getlistfromxml(path);
        ResultRes resultRes=null;
        ArrayList result = new ArrayList<>();
        if(getlistfromxml!=null&&getlistfromxml.size()>0){
            for(MonitorBaseInfo monitorBaseInfo:getlistfromxml){
                //当没有index
                if(StringUtils.isBlank(monitorBaseInfo.getIndex())){
                    //todo  根据dependid去bulk
                    //todo  根据dependid去bulk 留下来包含value的 去掉dependid 及value
                    List bulk1 = this.getBulk(Ip, monitorBaseInfo.getDependOid());
                    Iterator iterator = bulk1.iterator();
                    while(iterator.hasNext()){
                        String next1 = iterator.next();
                        if(!next1.contains(monitorBaseInfo.getOidValue())){
                            iterator.remove();
                        }
                    }
                    for(String ss:bulk1){
                        String remove = StringUtils.remove(StringUtils.remove(ss, monitorBaseInfo.getDependOid()), monitorBaseInfo.getOidValue());
                        String replace = remove.replace(".", "");
                        String substring = replace.substring(0, replace.indexOf("-"));
                        resultRes = new ResultRes();
                        resultRes.setMptype(monitorBaseInfo.getTypeId());
                        resultRes.setMpTypeName(monitorBaseInfo.getTypeName());
                        resultRes.setMindex(substring);
                        result.add(resultRes);
                    }
                    //输出结果查看
//                    System.out.println(result.toString());
                }
                //当index=-1
                if(StringUtils.isNotBlank(monitorBaseInfo.getIndex())&&monitorBaseInfo.getIndex().equals("-1")){
                    //todo  根据baseid去bulk 然后跟baseid 做对比 做过滤 留下来索引
                    List bulk1 = this.getBulk(Ip, monitorBaseInfo.getBaseOid());
                    //System.out.println("查出来的bulk1为======:"+bulk1);
                    Iterator iterator = bulk1.iterator();
                    while(iterator.hasNext()){
                        String next1 = iterator.next();
                        if(!next1.contains(monitorBaseInfo.getBaseOid())){
                            iterator.remove();
                        }
                    }
                 //   System.out.println("去除掉不包含baseoid的bulk为=="+bulk1);
                    for(String ss:bulk1){
                        String remove = StringUtils.remove(ss,monitorBaseInfo.getBaseOid());
                        String replace = remove.replace(".", "");
                        String substring = replace.substring(0, replace.indexOf("-"));
                        resultRes = new ResultRes();
                        resultRes.setMptype(monitorBaseInfo.getTypeId());
                        resultRes.setMpTypeName(monitorBaseInfo.getTypeName());
                        resultRes.setMindex(substring);
                        result.add(resultRes);
                    }
                }
                //当index==x
                if(StringUtils.isNotBlank(monitorBaseInfo.getIndex())&&!monitorBaseInfo.getIndex().equals("-1")){
                    resultRes = new ResultRes();
                    resultRes.setMptype(monitorBaseInfo.getTypeId());
                    resultRes.setMindex(monitorBaseInfo.getIndex());
                    resultRes.setMpTypeName(monitorBaseInfo.getTypeName());
                    result.add(resultRes);
                }
            }
            return result;
        }
        return new ArrayList<>();
    }
}

get 方式 获取某个oid 的准确值 

getbulk 获取其下的所有oid

walk 获取其下所有oid的值

next 获取下一个oid的值

你可能感兴趣的:(snmp工具类)