Snmp工具类

SnmpUtil类 


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
public class SnmpUtil {
    public static void main(String[] args) {
        SnmpUtil snmpUtil = new SnmpUtil.Builder()
                .setIp("")
                .setPort(0)
                .setVersion(SnmpConstants.version2c)
                .build();
        snmpUtil.walk("");
    }

    public static final int DEFAULT_VERSION = SnmpConstants.version2c;
    public static final String DEFAULT_PROTOCOL = "udp";
    public static final String DEFAULT_COMMUNITY = "public";
    public static final int DEFAULT_PORT = 161;
    public static final long DEFAULT_TIMEOUT = 3 * 1000L;
    public static final int DEFAULT_RETRY = 3;
    private CommunityTarget communityTarget;
    private Builder builder;

    private SnmpUtil() {

    }

    private SnmpUtil(Builder builder) {
        this.builder = builder;
        String protocol = StringUtils.isNotBlank(builder.getDefaultProtocol()) ? builder.getDefaultProtocol() : DEFAULT_PROTOCOL;
        int port = ObjectUtils.notEqual(builder.getPort(), null) ? builder.getPort() : DEFAULT_PORT;
        String community = StringUtils.isNotBlank(builder.getCommunity()) ? builder.getCommunity() : DEFAULT_COMMUNITY;
        Address address = GenericAddress.parse(protocol + ":" + builder.getIp() + "/" + port);
        communityTarget = new CommunityTarget(address, new OctetString(community));
        communityTarget.setTimeout(DEFAULT_TIMEOUT);
        communityTarget.setRetries(DEFAULT_RETRY);
    }

    public List walk(String oid) {
        List list = new ArrayList<>();
        Snmp snmp = null;
        try {
            TransportMapping transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            transport.listen();
            PDU pdu = new PDU();
            OID targetOID = new OID(oid);
            pdu.add(new VariableBinding(targetOID));
            boolean finished = false;
            while (!finished) {
                VariableBinding vb = null;
                ResponseEvent respEvent = snmp.getNext(pdu, communityTarget);
                PDU response = respEvent.getResponse();
                if (!ObjectUtils.notEqual(response, null)) {
                    finished = true;
                    break;
                }
                vb = response.get(0);
                finished = checkWalkFinished(targetOID, pdu, vb);
                if (!finished) {
                    String key = ObjectUtils.notEqual(vb.getOid(), null) ? vb.getOid().toString() : null;
                    String value = ObjectUtils.notEqual(vb.getVariable(), null) ? vb.getVariable().toString() : null;
                    KeyValuePair keyValuePair = new KeyValuePair(key, value, null, vb);
                    vb.getSyntax();
                    list.add(keyValuePair);
                    pdu.setRequestID(new Integer32(0));
                    pdu.set(0, vb);
                } else {
                    snmp.close();
                }
            }


        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            if(snmp != null){
                try {
                    snmp.close();
                }catch (IOException e){
                    snmp = null;
                    log.error(e.getMessage());
                }
            }
        }


        return list;
    }


    /**
     * 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) {
            log.info("[true] responsePDU.getErrorStatus() != 0 ");
            log.info(pdu.getErrorStatusText());
            finished = true;
        } else if (vb.getOid() == null) {
            log.info("[true] vb.getOid() == null");
            finished = true;
        } else if (vb.getOid().size() < targetOID.size()) {
            log.info("[true] vb.getOid().size() < targetOID.size()");
            finished = true;
        } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
            log.info("[true] targetOID.leftMostCompare() != 0");
            finished = true;
        } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
            log.info("[true] Null.isExceptionSyntax(vb.getVariable().getSyntax())");
            finished = true;
        } else if (vb.getOid().compareTo(targetOID) <= 0) {
            log.info("[true] Variable received is not "
                    + "lexicographic successor of requested " + "one:");
            log.info(vb.toString() + " <= " + targetOID);
            finished = true;
        }
        return finished;
    }

    public static class Builder {
        private String ip;
        private Integer port;
        private Integer version;
        private String defaultProtocol;
        private String community;

        //        private String oid;
        public Builder setDefaultProtocol(String defaultProtocol) {
            this.defaultProtocol = defaultProtocol;
            return this;
        }
//
//        public Builder setOid(String oid) {
//            this.oid = oid;
//            return this;
//        }

        public Builder setCommunity(String community) {
            this.community = community;
            return this;
        }

        public Builder setIp(String ip) {
            this.ip = ip;
            return this;
        }

        public Builder setPort(Integer port) {
            this.port = port;
            return this;
        }

        public Builder setVersion(Integer version) {
            this.version = version;
            return this;
        }

        public String getCommunity() {
            return community;
        }

        public String getIp() {
            return ip;
        }

        public Integer getPort() {
            return port;
        }

//        public String getOid() {
//            return oid;
//        }

        public Integer getVersion() {
            return version;
        }

        public String getDefaultProtocol() {
            return defaultProtocol;
        }

        public SnmpUtil build() {
            return new SnmpUtil(this);
        }
    }
}

 KeyValuePair类


import lombok.Data;
import org.apache.commons.lang3.ObjectUtils;

@Data
public class KeyValuePair implements Comparable {
    private String key;
    private String value;
    private Integer sort;

    private Object source;
    public KeyValuePair(){
        this.setSort(0);
    }
    public KeyValuePair(String key, String value) {
        this();
        this.setKey(key);
        this.setValue(value);
        this.setSort(0);
    }

    public KeyValuePair(String key, String value, Integer sort) {
        this(key, value);
        this.setSort(sort);
    }

    public KeyValuePair(String key, String value, Integer sort, Object source) {
        this(key, value, sort);
        this.setSource(source);
    }

    @Override
    public int compareTo(KeyValuePair o) {
        return o.getSort() - this.getSort();
    }
}

你可能感兴趣的:(Snmp,Snmp协议)