Skip to content

Instantly share code, notes, and snippets.

@kimhu
Created August 7, 2014 08:05
Show Gist options
  • Save kimhu/7fa6e43e2f94f9a0569f to your computer and use it in GitHub Desktop.
Save kimhu/7fa6e43e2f94f9a0569f to your computer and use it in GitHub Desktop.
This class can catch the AUTH_PRIV v3 trap, also can catch the snmp v1, v2 and v3 normal trap. Contains SNMP4j v1 and v3 trap sender example.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testsnmp4j;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.snmp4j.*;
import org.snmp4j.mp.*;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;
import org.snmp4j.util.*;
/**
*
* @author kim_hu
*
*/
public class MultiThreadedTrapReceiver implements CommandResponder {
private Address address = GenericAddress.parse("0.0.0.0/162");
private int numDispatcherThreads = 2;
private OID authProtocol = AuthMD5.ID;
private OID privProtocol = PrivDES.ID;
private OctetString securityName = new OctetString("MD5DES");
private OctetString privPassphrase = new OctetString("MD5DESUserPrivPassword");
private OctetString authPassphrase = new OctetString("MD5DESUserAuthPassword");
public MultiThreadedTrapReceiver() {
try {
listen();
} catch (IOException ex) {
Logger.getLogger(MultiThreadedTrapReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
}
public synchronized void listen() throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool =
ThreadPool.create("DispatcherPool", numDispatcherThreads);
MessageDispatcher mtDispatcher =
new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
// add message processing models
mtDispatcher.addMessageProcessingModel(new MPv1());
mtDispatcher.addMessageProcessingModel(new MPv2c());
mtDispatcher.addMessageProcessingModel(new MPv3(new OctetString(MPv3.createLocalEngineID()).getValue()));
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
Snmp snmp = new Snmp(mtDispatcher, transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
// Add the configured user to the USM
addUsmUser(snmp);
snmp.addCommandResponder(this);
transport.listen();
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
private void addUsmUser(Snmp snmp) {
snmp.getUSM().addUser(securityName, new UsmUser(securityName,
authProtocol,
authPassphrase,
privProtocol,
privPassphrase));
}
@Override
public void processPdu(CommandResponderEvent respEvnt) {
System.out.println(respEvnt.getPDU());
InetAddress pduAgentAddress = null;
//System.out.println(respEvnt.getPDU() + " recieved;");
//this.setPdu(respEvnt.getPDU());
OctetString community = new OctetString(respEvnt.getSecurityName());
System.out.println("community: " + community.toString());
//handle the SNMP v1
if (respEvnt.getPDU().getType() == PDU.V1TRAP) {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
Logger.getLogger(MultiThreadedTrapReceiver1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress() + "; port: " + nPort);
} else {
Address address = respEvnt.getPeerAddress();
String hostName = address.toString().split("/")[0];
int nPort = Integer.parseInt(address.toString().split("/")[1]);
try {
pduAgentAddress = InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
Logger.getLogger(MultiThreadedTrapReceiver1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("hostname: " + pduAgentAddress.getHostAddress() + "; port: " + nPort);
}
}
public static void main(String[] args) {
MultiThreadedTrapReceiver trap = new MultiThreadedTrapReceiver();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testsnmp4j;
import java.io.IOException;
import org.snmp4j.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;
/**
*
* @author kim_hu
* SNMP4J v1 trap sender example
*
*/
public class SnmpUtilSendTrapV1 {
private Snmp snmp = null;
private Address targetAddress = null;
public void initComm() throws IOException {
targetAddress = GenericAddress.parse("udp:127.0.0.1/162");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
transport.listen();
}
public void sendPDU() throws IOException {
//Create Target
CommunityTarget comtarget = new CommunityTarget();
comtarget.setVersion(SnmpConstants.version1);
comtarget.setAddress(targetAddress);
//comtarget.setRetries(2);
comtarget.setTimeout(5000);
comtarget.setSecurityName(new OctetString("public"));
//Create PDU for V1
PDUv1 pdu = new PDUv1();
pdu.setType(PDU.V1TRAP);
pdu.add(new VariableBinding(new OID("1.3.6.1.2.3377.10.1.1.1.1"),
new OctetString("SnmpTrapv1")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.3377.10.1.1.1.2"),
new OctetString("JavaEE")));
//Send the PDU
snmp.send(pdu, comtarget);
}
public static void main(String[] args) {
try {
SnmpUtilSendTrapV1 util = new SnmpUtilSendTrapV1();
util.initComm();
util.sendPDU();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testsnmp4j;
import java.io.IOException;
import java.util.Vector;
import org.snmp4j.*;
import org.snmp4j.event.*;
import org.snmp4j.mp.*;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;
/**
*
* @author kim_hu
* SNMP4j v3 trap sender example
*/
public class SnmpUtilSendTrapV3 {
private Snmp snmp = null;
private Address targetAddress = null;
public void initComm() throws IOException {
targetAddress = GenericAddress.parse("127.0.0.1/162");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
snmp.listen();
}
/**
* send trap
*
* @throws IOException
*/
public void sendPDU() throws IOException {
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
// snmp version
target.setVersion(SnmpConstants.version3);
//target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
usm.setEngineDiscoveryEnabled(true);
SecurityModels.getInstance().addSecurityModel(usm);
UsmUser user = new UsmUser(new OctetString("MD5DES"),
AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"),
PrivDES.ID,
new OctetString("MD5DESUserPrivPassword"));
snmp.getUSM().addUser(new OctetString("MD5DES"), user);
// create PDU
ScopedPDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.0"),
new OctetString("SnmpTrapv3")));
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0"),
new OctetString("JavaEE")));
pdu.setType(PDU.TRAP);
// send PDU to Agent and recieve Response
ResponseEvent respEvnt = snmp.send(pdu, target);
// analyze 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);
System.out.println(recVB.getOid() + " : " + recVB.getVariable());
}
}
snmp.close();
}
public static void main(String[] args) {
try {
SnmpUtilSendTrapV3 util = new SnmpUtilSendTrapV3();
util.initComm();
util.sendPDU();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@AshishMamgain-01
Copy link

how to store trap from socket to in a queue before processing them by process pdu

@vinsonLan
Copy link

good job

@sayedsadat344
Copy link

MultiThreadedTrapReceiver1

what is this class?

@simsim-png
Copy link

simsim-png commented Mar 8, 2023

where is the process PDU for Trap v3 ?

@hczs
Copy link

hczs commented Sep 14, 2023

This has been very helpful to me, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment