snmp server and client implementation, based on snmp4j

snmp protocol: a simple network management protocol, often used to manage network devices, in java development, using snmp4j as the underlying snmp component is more popular,
the following example briefly describes how to build a simple snmp server and client


snmp server based on snmp4j
package com.gbcom.protocol.snmp;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Vector;

import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.MessageDispatcherImpl;
import org.snmp4j.MessageException;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.mp.MPv1;
import org.snmp4j.mp.MPv2c;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.StateReference;
import org.snmp4j.mp.StatusInformation;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TcpAddress;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.MultiThreadedMessageDispatcher;
import org.snmp4j.util.ThreadPool;

/**
 * This class is used to monitor the Trap information of the agent process
 *
 * @author syz
 *
 * @date 3:28:28 PM
 * @version v1.0.0
 * @see SnmpTrapReceiver
 */
public class SnmpTrapReceiver implements CommandResponder {
	private MultiThreadedMessageDispatcher dispatcher;
	private Snmp snmp = null;
	private Address listenAddress;
	private ThreadPool threadPool;

	public SnmpTrapReceiver() {
	}

	//Initialize the listener.
	private void init() throws UnknownHostException, IOException {
		threadPool = ThreadPool.create("Trap", 2);
		dispatcher = new MultiThreadedMessageDispatcher(threadPool,
				new MessageDispatcherImpl());
		listenAddress = GenericAddress.parse(System.getProperty(
				"snmp4j.listenAddress", "udp:127.0.0.1/162")); // local IP and listening port
		TransportMapping transport;
		// Process the TCP and UDP protocols
		if (listenAddress instanceof UdpAddress) {
			transport = new DefaultUdpTransportMapping(
					(UdpAddress) listenAddress);
		} else {
			transport = new DefaultTcpTransportMapping(
					(TcpAddress) listenAddress);
		}
		snmp = new Snmp(dispatcher, transport);
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
		snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
		USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
				MPv3.createLocalEngineID()), 0);
		SecurityModels.getInstance().addSecurityModel(usm);
		snmp.listen();
	}

	public void run() {
		try {
			init();
			snmp.addCommandResponder(this);
			System.out.println("Start monitoring Trap information!");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Implement the processPdu method of CommandResponder, which is used to process incoming requests, PDUs and other information. When a trap is received, it will automatically enter this method
	 *
	 * @param respEvnt
	 *
	 */
	public void processPdu(CommandResponderEvent respEvnt) {
		if (respEvnt != null && respEvnt.getPDU() != null) {
			PDU src_pdu = respEvnt.getPDU();
			// need to confirm the trap
			if (src_pdu.getType() == PDU.INFORM) {
				PDU responsePDU = new PDU(src_pdu);
				responsePDU.setErrorIndex(0);
				responsePDU.setErrorStatus(0);
				responsePDU.setType(PDU.RESPONSE);
				StatusInformation statusInfo = new StatusInformation ();
				StateReference stateRef = respEvnt.getStateReference();
				try {
					respEvnt.getMessageDispatcher().returnResponsePdu(
							respEvnt.getMessageProcessingModel(),
							respEvnt.getSecurityModel(),
							respEvnt.getSecurityName(),
							respEvnt.getSecurityLevel(), responsePDU,
							respEgt.getMaxSizeResponsePDU (), stateRef,
							statusInfo);

				} catch (MessageException msgEx) {
					msgEx.printStackTrace();
				}
			}

			Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getPDU()
					.getVariableBindings();
			for (int i = 0; i < recVBs.size(); i++) {
				VariableBinding recVB = recVBs.elementAt(i);
				System.out
						.println(recVB.getOid() + " : " + recVB.getVariable());
			}
		}

	}

	public static void main(String[] args) {
		// start the service
		SnmpTrapReceiver multithreadedtrapreceiver = new SnmpTrapReceiver();
		multithreadedtrapreceiver.run();
	}

}



snmp client
encapsulation common methods
package com.gbcom.protocol.snmp;

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

import org.apache.log4j.Logger;
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.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

/**
 * This class is used to send information to the management process {@code Trap GET SET}
 *
 * @author syz
 * @date 5:02:20 PM
 * @version v1.0.0
 * @see SnmpSender
 */
public class SnmpSender {
	private static final Logger LOG = Logger.getLogger(SnmpSender.class);
	private Snmp snmp = null;

	private Address targetAddress = null;

	public void initComm() throws IOException {
		// Set the IP and port of the management process
		targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
		TransportMapping transport = new DefaultUdpTransportMapping();
		snmp = new Snmp(transport);
		transport.listen();
		LOG.info("init SNMP object succes !!    target = udp:127.0.0.1/161");
	}

	/**
	 * Send Trap message to management process
	 *
	 * @throws IOException
	 */
	public void sendTrap() throws IOException { targetAddress = GenericAddress.parse("udp:127.0.0.1/162");
		// set target
		CommunityTarget target = new CommunityTarget();
		target.setAddress(targetAddress);
		// The number of retries when the communication is unsuccessful
		target.setRetries(2);
		// overtime time
		target.setTimeout(1500);
		// snmp version
		target.setVersion(SnmpConstants.version2c);
		// create PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),
				new OctetString("SnmpTrap")));
		pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"),
				new OctetString("JavaEE")));
		pdu.setType(PDU.TRAP);

		// Send PDU to Agent and receive Response
		ResponseEvent respEvnt = snmp.send(pdu, target);
		// Parse Response
		readResponse(respEvnt);
//		if (respEvnt != null && respEvnt.getResponse() != null) {
//			Vector<VariableBinding> recVBs = respEvnt.getResponse()
// .getVariableBindings();
//			for (int i = 0; i < recVBs.size(); i++) {
//				VariableBinding recVB = recVBs.elementAt(i);
//				System.out
//						.println(recVB.getOid() + " : " + recVB.getVariable());
//			}
//		}
	}

	public ResponseEvent sendPDU(PDU pdu) throws IOException {
		// set target
		CommunityTarget target = new CommunityTarget();
		target.setCommunity(new OctetString("public"));
		target.setAddress(targetAddress);
		// The number of retries when the communication is unsuccessful
		target.setRetries(1);
		// overtime time
		target.setTimeout(1500);
		target.setVersion(SnmpConstants.version2c);
		// Send PDU to Agent and return Response
		return snmp.send(pdu, target);
	}

	public void doSet() throws IOException {
		// set PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5,
				0 }), new OctetString("SNMPTEST")));
		pdu.setType(PDU.SET);
		readResponse(sendPDU(pdu));
	}

	public void doGet() throws IOException {
		// get PDU
		PDU pdu = new PDU();
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 1,
				0 })));
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 2,
				0 })));
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 3,
				0 })));
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 4,
				0 })));
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 5,
				0 })));
		pdu.add(new VariableBinding(new OID(new int[] { 1, 3, 6, 1, 2, 1, 1, 6,
				0 })));
		pdu.setType(PDU.GET);
		readResponse(sendPDU(pdu));
	}

	private void readResponse(ResponseEvent respEvnt) {
		// Parse Response
		if (respEvnt != null && respEvnt.getResponse() != null) {
			Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getResponse()
					.getVariableBindings();
			for (int i = 0; i < recVBs.size(); i++) {
				VariableBinding recVB = recVBs.elementAt(i);
				LOG.info("THREAD NUM--"+Thread.currentThread() +  recVB.getOid() + " : " + recVB.getVariable());
			}
		}
	}

	
	
	
	public void doWork(){
		for(int i=0;i<1;i++){
			Thread t  = new Thread(new WorkThread());
			t.start();
		}
	}
	
	class WorkThread implements Runnable{

		@Override
		public void run() {
			while(!Thread.currentThread().interrupted()){
				try {
//					doGet();
// doSet();
					Thread.sleep(1*1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
					LOG.error("THREAD NUM--"+Thread.currentThread() + "InterruptedException",e);
				} catch (Exception e) {
					e.printStackTrace ();
					LOG.error("THREAD NUM--"+Thread.currentThread() + "other Exception",e);
					continue;
				}
			}
				
		}
		
	}
	
	
	public static void main(String[] args) {
		try {
			SnmpSender util = new SnmpSender();
			util.initComm ();
// util.sendTrap ();
			LOG.info("---  DO GET --");
//			util.doGet();
			LOG.info("----do set---");
// util.doSet ();
			util.doWork ();
			

		} catch (IOException e) {
			e.printStackTrace ();
		}
	}
	

}

Note that the correct operation of the sender needs to open the agent. In general, the device side implements the snmp agent, and the server implements the snmp server.


If you need the snmp4j component to be developed as the snmp protocol, you can refer to the above example.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326563569&siteId=291194637