web123456

Java implements snmp SNMP4J to monitor switches through get, trap, and walk. With API

package com.snmp.collection.get_collection.collectionforII; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.snmp4j.*; import org.snmp4j.event.ResponseEvent; import org.snmp4j.mp.MPv1; import org.snmp4j.mp.MPv2c; import org.snmp4j.mp.MPv3; import org.snmp4j.mp.SnmpConstants; import org.snmp4j.security.*; import org.snmp4j.smi.*; import org.snmp4j.transport.DefaultTcpTransportMapping; import org.snmp4j.transport.DefaultUdpTransportMapping; import org.snmp4j.util.MultiThreadedMessageDispatcher; import org.snmp4j.util.ThreadPool; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.util.*; /** * @description: get data * @author: yghhz * @create: 2020-11-15 10:14 **/ public class MultiThreadedGetDemo { private static final Logger LOGGER = LogManager.getLogger(MultiThreadedGetDemo.class); //username private String username = "nms2-admin"; //Authorization Password private String authPassword = "hello123"; //Data encryption password private String privPassword = "hello123"; //trap address private String address = "udp:192.160.0.1/162"; //get address private String addressGet = "udp:192.160.0.2/161"; private MultiThreadedMessageDispatcher dispatcher; private Snmp snmp = null; private Address listenAddress; private ThreadPool threadPool; public MultiThreadedGetDemo() { } public void initSnmp() throws IOException { //1. Initialize multi-threaded message forwarding class MessageDispatcher messageDispatcher = new MessageDispatcherImpl(); //Three processing models should be added. If snmp initialization uses Snmp(TransportMapping<? extends Address> transportMapping), there is no need to add it messageDispatcher.addMessageProcessingModel(new MPv1()); messageDispatcher.addMessageProcessingModel(new MPv2c()); // When you want to support snmpV3 version, you need to configure user OctetString localEngineID = new OctetString(MPv3.createLocalEngineID()); USM usm = new USM(SecurityProtocols.getInstance().addDefaultProtocols(), localEngineID, 0); OctetString userName1 = new OctetString(username); OctetString authPass = new OctetString(authPassword); OctetString privPass = new OctetString(privPassword); UsmUser user = new UsmUser(userName1, AuthMD5.ID, authPass, PrivAES128.ID, privPass); usm.addUser(user.getSecurityName(), user); messageDispatcher.addMessageProcessingModel(new MPv3(usm)); //2. Create transportMapping ip as a local ip, and you can not set it TransportMapping<?> transportMapping = new DefaultUdpTransportMapping(); //3. Officially create snmp snmp = new Snmp(messageDispatcher, transportMapping); //Open monitoring snmp.listen(); } private Target createTarget(String oid) { Target target = null; int version = 1; if (!(version == SnmpConstants.version3 || version == SnmpConstants.version2c || version == SnmpConstants.version1)) { //("parameter version exception"); return target; } if (version == SnmpConstants.version3) { target = new UserTarget(); //SnmpV3 needs to set the security level and security name, where the security name is to create the new OctetString("SNMPV3") for the user settings of snmp. target.setSecurityLevel(SecurityLevel.AUTH_PRIV); target.setSecurityName(new OctetString(this.username)); } else { //SnmpV1 and snmpV2 need to specify the group name target = new CommunityTarget(); ((CommunityTarget) target).setCommunity(new OctetString(this.username)); if (version == SnmpConstants.version2c) { target.setSecurityModel(SecurityModel.SECURITY_MODEL_SNMPv2c); } } target.setVersion(version); // Must specify, if there is no setting, an error will be reported. target.setAddress(GenericAddress.parse(this.addressGet)); target.setRetries(3); target.setTimeout(2000); return target; } private static PDU createPDU(int version, int type, String oid) { PDU pdu = null; if (version == SnmpConstants.version3) { pdu = new ScopedPDU(); } else { pdu = new PDUv1(); } pdu.setType(type); //You can add multiple variables oid /*for(String oid:oids){ (new VariableBinding(new OID(oid))); }*/ pdu.add(new VariableBinding(new OID(oid))); return pdu; } /** * GET method request * @param oid */ public List<Map> snmpGet(String oid) { try { LOGGER.info("getfangshi"); List<Map> list = new ArrayList<Map>(); //1. Initialize snmp and enable listening initSnmp(); //2. Create the target object Target target = this.createTarget(oid); //3. Create a message PDU pdu = createPDU(1, PDU.GET, oid); //4. Send a message and get the return result ResponseEvent responseEvent = snmp.send(pdu, target); PDU response = responseEvent.getResponse(); if (response == null) { System.out.println("TimeOut..."); } else { if (response.getErrorStatus() == PDU.noError) { //The return value obtained by get Vector<? extends VariableBinding> vbs = response.getVariableBindings(); for (VariableBinding vb : vbs) { Map map = new HashMap(); map.put("value",vb.getVariable()); System.out.println("():" + vb.getVariable()); System.out.println("OID:" + vb.getVariable()); LOGGER.info("OIDvALUE" + vb.getVariable()); list.add(map); } return list; } else { System.out.println("Error:" + response.getErrorStatusText()); } } } catch (IOException e) { e.printStackTrace(); } return null; } //Open the main method of monitoring. public static void main(String[] args) throws IOException { MultiThreadedGetDemo multithreadedtrapreceiver = new MultiThreadedGetDemo(); multithreadedtrapreceiver.run(); } public void run() { try { System.out.println("Start listen to get information!"); LOGGER.info("Memory"); String devOid = "1.3.6.1.4.1.25506.2.6.1.1.1.1.8"; this.snmpGet(devOid); LOGGER.info("cpu"); String devOid1 = "1.3.6.1.4.1.25506.2.6.1.1.1.1.6"; this.snmpGet(devOid1); LOGGER.info("Running time"); String data1 = "1.3.6.1.2.1.1.3.0"; this.snmpGet(data1); } catch (Exception ex) { ex.printStackTrace(); } } }