我使用SNMP4J库编写代理代理(SNMP v2c)。
我从here的代码开始。
委托代理(TestProxy
)收到管理代理(MA,TrapSenderVersion2
对象)发送的陷阱,虽然陷阱永远不会到达网络管理系统(NMS, TrapReceiver
)的对象。
您能否给我一些好的建议,最好提供适合您的代理商样本?
TestProxy.java
public class TestProxy extends BaseAgent {
//MA - Management Agent which should report its trap to NMS
public static final String ADDRESS_MA = "127.0.0.1/2163";//"172.19.0.1/161";
//NMS - Network Management System which should receive trap from MA
public static final String ADDRESS_NMS = "127.0.0.1/2162";//"10.30.34.17/162";
// initialize Log4J logging
static {
LogFactory.setLogFactory(new Log4jLogFactory());
ma = new UdpAddress(ADDRESS_MA);//"172.19.0.1/161");
nms = new UdpAddress(ADDRESS_NMS);//"10.30.34.17/162");
}
static final UdpAddress ma; // Managed Agent
static final UdpAddress nms; // Network Management System
protected String address;
/**
* Creates the test agent with a file to read and store the boot counter and
* a file to read and store its configuration.
*
* @param bootCounterFile a file containing the boot counter in serialized
* form (as expected by BaseAgent).
* @param configFile a configuration file with serialized management
* information.
* @throws IOException if the boot counter or config file cannot be read
* properly.
*/
public TestProxy(File bootCounterFile, File configFile) throws IOException {
super(bootCounterFile, configFile, null);//new CommandProcessor(new OctetString(MPv3.createLocalEngineID())));
setAgent(new CommandProcessor(new OctetString(MPv3.createLocalEngineID())) {
@Override
public void processPdu(CommandResponderEvent event) {
processTrap(event);// super.processPdu(event);
}
});
}
public void processTrap(CommandResponderEvent event) {
System.out.println("!!! inside processTrap ");
OctetString contextEngineID;
OctetString contextName;
if (event.getPDU() instanceof ScopedPDU) {
ScopedPDU pdu = (ScopedPDU) event.getPDU();
contextEngineID = pdu.getContextEngineID();
contextName = pdu.getContextName();
} else {
contextEngineID = new OctetString(getInternalEngineID(event.getPeerAddress()));
contextName = new OctetString();
}
System.out.println("secName: " + new String(event.getSecurityName()));
PDU pdu = event.getPDU();
System.out.println("Trap Type = " + pdu.getType());
System.out.println("Variables = " + pdu.getVariableBindings());
ProxyForwardRequest request = new ProxyForwardRequest(event, new CoexistenceInfo(null, contextEngineID, contextName));
boolean forawrdResult = defaultProxyForwarder.forward(request);
System.out.println("contextEngineID: " + contextEngineID + "; contextName:" + contextName + "; forawrdResult: " + forawrdResult);
}
@Override
public void init() throws IOException {
super.init();
}
@Override
protected void registerManagedObjects() {
}
@Override
protected void addNotificationTargets(SnmpTargetMIB targetMIB,
SnmpNotificationMIB notificationMIB) {
targetMIB.addDefaultTDomains();
TDomainAddressFactoryImpl factory = new TDomainAddressFactoryImpl();
System.out.println("factory.getTransportDomain(nms)[0]: " + factory.getTransportDomain(nms)[0] + " factory.getAddress(nms): " + factory.getAddress(nms));
targetMIB.addTargetAddress(new OctetString("notification"),
factory.getTransportDomain(nms)[0],
factory.getAddress(nms),
200, 1,
new OctetString("notify"),
new OctetString("v2c"),
StorageType.permanent);
targetMIB.addTargetParams(new OctetString("v2c"),
MessageProcessingModel.MPv2c,
SecurityModel.SECURITY_MODEL_SNMPv2c,
new OctetString("public"),
SecurityLevel.NOAUTH_NOPRIV,
StorageType.permanent);
notificationMIB.addNotifyEntry(new OctetString("default"),
new OctetString("notify"),
SnmpNotificationMIB.SnmpNotifyTypeEnum.trap,
StorageType.permanent);
}
@Override
protected void addViews(VacmMIB vacm) {
vacm.addGroup(SecurityModel.SECURITY_MODEL_SNMPv2c,
new OctetString("cpublic"),
new OctetString("v1v2group"),
StorageType.nonVolatile);
vacm.addAccess(new OctetString("v1v2group"), new OctetString("public"),
SecurityModel.SECURITY_MODEL_ANY,
SecurityLevel.NOAUTH_NOPRIV,
MutableVACM.VACM_MATCH_EXACT,
new OctetString("fullReadView"),
new OctetString("fullWriteView"),
new OctetString("fullNotifyView"),
StorageType.nonVolatile);
vacm.addViewTreeFamily(new OctetString("fullReadView"), new OID("1.3"),
new OctetString(), VacmMIB.vacmViewIncluded,
StorageType.nonVolatile);
}
@Override
protected void addUsmUser(USM usm) {
}
/**
* add Community-based agent for proxy-forwarding.
*
* @param communityName
* @param address
*/
public void addCommunityAgent(OctetString communityName, Address address) {
TDomainAddressFactoryImpl factory = new TDomainAddressFactoryImpl();
// add community-table
OctetString snmpCommunityIndex = new OctetString("uniqueCommunityIndex");
OctetString secName = new OctetString("uniqueSecName");
OctetString snmpCommunityTransportTag = new OctetString("uniqueTransportTag");
OctetString contextEngineID = new OctetString(getInternalEngineID(address));
System.out.println(contextEngineID);
Variable[] vars = new Variable[]{
communityName, // community name
secName, // security name
contextEngineID, // context engine id
new OctetString(), // context name
snmpCommunityTransportTag, // transport tag
new Integer32(StorageType.volatile_), // storage type
new Integer32(RowStatus.active) // row status
};
MOTableRow row = getSnmpCommunityMIB().getSnmpCommunityEntry().createRow(
snmpCommunityIndex.toSubIndex(true), vars);
getSnmpCommunityMIB().getSnmpCommunityEntry().addRow(row);
// add target-parameters-table
OctetString snmpTargetParamsName = new OctetString("uniqueTargetParamsName");
getSnmpTargetMIB().addTargetParams(
snmpTargetParamsName,
MessageProcessingModel.MPv2c, // MessageProcessingModel.MPv1,
SecurityModel.SECURITY_MODEL_SNMPv2c,// SecurityModel.SECURITY_MODEL_SNMPv1,
communityName,
SecurityLevel.NOAUTH_NOPRIV,
StorageType.volatile_);
// add target-address-table
OctetString snmpTargetAddrName = new OctetString("uniqueTargetAddrName");
System.out.println("factory.getTransportDomain(address)[0]: " + factory.getTransportDomain(address)[0] + " factory.getAddress(address): " + factory.getAddress(address));
getSnmpTargetMIB().addTargetAddress(
snmpTargetAddrName,
factory.getTransportDomain(address)[0],
factory.getAddress(address),
1500,
1,
snmpCommunityTransportTag,
snmpTargetParamsName,
StorageType.volatile_);
// add proxy-table(trap)
OctetString snmpProxyName1 = new OctetString("uniqueProxyName1");
getSnmpProxyMIB().addProxyEntry(
snmpProxyName1,
ProxyForwarder.PROXY_TYPE_NOTIFY,
contextEngineID,
new OctetString(),
snmpTargetParamsName,
null,
new OctetString("nms"),
StorageType.volatile_);
// add proxy-table(get)
OctetString snmpProxyName2 = new OctetString("uniqueProxyName2");
getSnmpProxyMIB().addProxyEntry(
snmpProxyName2,
ProxyForwarder.PROXY_TYPE_READ,
contextEngineID,
new OctetString(),
new OctetString("SHA"),
snmpTargetAddrName,
null,
StorageType.volatile_);
}
byte[] getInternalEngineID(Address address) {
// NOTE: generate EngineID without PortNumber for return-value (ID) be same
// at request/response and notify.
OctetString id;
if (address instanceof IpAddress) {
id = new OctetString(((IpAddress) address).getInetAddress().getAddress());
} else {
id = new OctetString();
}
return MPv3.createLocalEngineID(id);
}
@Override
protected void initTransportMappings() throws IOException {
transportMappings = new TransportMapping[1];
Address addr = GenericAddress.parse(address);
System.out.println("address: " + address);
TransportMapping tm = TransportMappings.getInstance().createTransportMapping(addr);
transportMappings[0] = tm;
}
@Override
protected void unregisterManagedObjects() {
// here we should unregister those objects previously registered...
}
@Override
protected void addCommunities(SnmpCommunityMIB communityMIB) {
Variable[] com2sec = new Variable[]{
new OctetString("public"), // community name
new OctetString("cpublic"), // security name
getAgent().getContextEngineID(), // local engine ID
new OctetString("public"), // default context name
new OctetString(), // transport tag
new Integer32(StorageType.nonVolatile), // storage type
new Integer32(RowStatus.active) // row status
};
MOTableRow row = communityMIB.getSnmpCommunityEntry().createRow(
new OctetString("public2public").toSubIndex(true), com2sec);
communityMIB.getSnmpCommunityEntry().addRow(row);
}
@Override
protected void registerSnmpMIBs() {
super.registerSnmpMIBs();
}
public static void main(String[] args) {
String address;
if (args.length > 0) {
address = args[0];
} else {
address = "0.0.0.0/2161";
}
BasicConfigurator.configure();
try {
final TestProxy testProxyAgent = new TestProxy(new File(""), new File(""));//new File("SNMP4JTestAgentBC.cfg"), new File("SNMP4JTestAgentConfig.cfg"));
testProxyAgent.address = address;
testProxyAgent.init();
testProxyAgent.loadConfig(ImportModes.UPDATE_CREATE);
testProxyAgent.addShutdownHook();
testProxyAgent.getServer().addContext(new OctetString("public"));
testProxyAgent.finishInit();
// NOTE: add SNMPv1-Trap (community-name: private) from Managed-Agent 'ma' as ProxyForward target.
testProxyAgent.addCommunityAgent(new OctetString("private"), ma);
testProxyAgent.run();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex1) {
break;
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
TrapReceiver.java
public class TrapReceiver implements CommandResponder {
public synchronized void listen(TransportIpAddress address) throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
MessageDispatcher mDispathcher = new MultiThreadedMessageDispatcher(
threadPool, new MessageDispatcherImpl());
// add message processing models
mDispathcher.addMessageProcessingModel(new MPv1());
mDispathcher.addMessageProcessingModel(new MPv2c());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
// Create Target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
Snmp snmp = new Snmp(mDispathcher, transport);
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on " + address);
try {
this.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* This method will be called whenever a pdu is received on the given port
* specified in the listen() method
*
* @param cmdRespEvent
*/
@Override
public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
System.out.println("Received PDU...");
PDU pdu = cmdRespEvent.getPDU();
if (pdu != null) {
System.out.println("Trap Type = " + pdu.getType());
System.out.println("Variables = " + pdu.getVariableBindings());
if (pdu.getType() == PDU.INFORM) {
System.out.println("INFORM message received");
pdu.setErrorIndex(0);
pdu.setErrorStatus(0);
pdu.setType(PDU.RESPONSE);
StatusInformation statusInformation = new StatusInformation();
StateReference ref = cmdRespEvent.getStateReference();
try {
System.out.println(cmdRespEvent.getPDU());
cmdRespEvent.getMessageDispatcher().returnResponsePdu(
cmdRespEvent.getMessageProcessingModel(),
cmdRespEvent.getSecurityModel(),
cmdRespEvent.getSecurityName(),
cmdRespEvent.getSecurityLevel(),
pdu,
cmdRespEvent.getMaxSizeResponsePDU(),
ref,
statusInformation);
} catch (MessageException ex) {
System.err.println("Error while sending response: " + ex.getMessage());
LogFactory.getLogger(TrapReceiver.class).error(ex);
}
}
}
}
public static void main(String[] args) {
LogFactory.setLogFactory(new Log4jLogFactory());
BasicConfigurator.configure();
TrapReceiver snmp4jTrapReceiver = new TrapReceiver();
try {
snmp4jTrapReceiver.listen(new UdpAddress(TestProxy.ADDRESS_NMS));
} catch (IOException e) {
LogFactory.getLogger(TrapReceiver.class).error(e);
}
}
}
TrapSenderVersion2.java
public class TrapSenderVersion2 {
public static final String community = "private";
// Sending Trap for sysLocation of RFC1213
public static final String Oid = "1.3.6.1.2.1.100.1.1";//".1.3.6.1.2.1.1.8";
//IP of Local Host
public static final String ipAddress = "127.0.0.1";
//Ideally Port 162 should be used to send receive Trap, any other available Port can be used
public static final int port = 2161;
/**
* This methods sends the V1 trap to the localhost on the given port
*/
public void sendTrap_Version2() {
try {
// Create Transport Mapping
TransportMapping transport = new DefaultUdpTransportMapping(new UdpAddress(TestProxy.ADDRESS_MA));
transport.listen();
// Create Target
CommunityTarget cTarget = new CommunityTarget();
cTarget.setCommunity(new OctetString(community));
cTarget.setVersion(SnmpConstants.version2c);
cTarget.setAddress(new UdpAddress(ipAddress + "/" + port));
cTarget.setRetries(2);
cTarget.setTimeout(5000);
// Create PDU for V2
PDU pdu = new PDU();
// need to specify the system up time
pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(Oid)));
pdu.add(new VariableBinding(SnmpConstants.snmpTrapAddress, new IpAddress(ipAddress)));
pdu.add(new VariableBinding(new OID(Oid), new OctetString("Major")));
pdu.setType(PDU.NOTIFICATION);
// Send the PDU
Snmp snmp = new Snmp(transport);
System.out.println("Sending V2 Trap... Check Wheather NMS is Listening or not? ");
snmp.notify(pdu, cTarget);
snmp.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TrapSenderVersion2 trapV2 = new TrapSenderVersion2();
trapV2.sendTrap_Version2();
}
}