本文整理了Java中org.snmp4j.Snmp
类的一些代码示例,展示了Snmp
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Snmp
类的具体详情如下:
包路径:org.snmp4j.Snmp
类名称:Snmp
[英]The Snmp class is the core of SNMP4J. It provides functions to send and receive SNMP PDUs. All SNMP PDU types can be send. Confirmed PDUs can be sent synchronously and asynchronously.
The Snmp class is transport protocol independent. Support for a specific TransportMapping instance is added by calling the #addTransportMapping(TransportMapping transportMapping) method or creating a Snmp instance by using the non-default constructor with the corresponding transport mapping. Transport mappings are used for incoming and outgoing messages.
To setup a default SNMP session for UDP transport and with SNMPv3 support the following code snippet can be used:
Address targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
How a synchronous SNMPv3 message with authentication and privacy is then sent illustrates the following code snippet:
// add user to the USM
snmp.getUSM().addUser(new OctetString("MD5DES"),
new UsmUser(new OctetString("MD5DES"),
AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"),
PrivDES.ID,
new OctetString("MD5DESUserPrivPassword")));
// create the target
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(1);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
// create the PDU
PDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6")));
pdu.setType(PDU.GETNEXT);
// send the PDU
ResponseEvent response = snmp.send(pdu, target);
// extract the response PDU (could be null if timed out)
PDU responsePDU = response.getResponse();
// extract the address used by the agent to send the response:
Address peerAddress = response.getPeerAddress();
An asynchronous SNMPv1 request is sent by the following code:
// setting up target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
// creating PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,1})));
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,2})));
pdu.setType(PDU.GETNEXT);
// sending request
ResponseListener listener = new ResponseListener() {
public void onResponse(ResponseEvent event) {
// Always cancel async request when response has been received
// otherwise a memory leak is created! Not canceling a request
// immediately can be useful when sending a request to a broadcast
// address.
((Snmp)event.getSource()).cancel(event.getRequest(), this);
System.out.println("Received response PDU is: "+event.getResponse());
}
};
snmp.sendPDU(pdu, target, null, listener);
Traps (notifications) and other SNMP PDUs can be received by adding the following code to the first code snippet above:
CommandResponder trapPrinter = new CommandResponder() {
public synchronized void processPdu(CommandResponderEvent e) {
PDU command = e.getPDU();
if (command != null) {
System.out.println(command.toString());
}
}
};
snmp.addCommandResponder(trapPrinter);
[中]Snmp类是SNMP4J的核心。它提供发送和接收SNMP PDU的功能。可以发送所有SNMP PDU类型。已确认的PDU可以同步和异步发送。
Snmp类与传输协议无关。通过调用#addTransportMapping(TransportMapping-TransportMapping)方法或使用带有相应传输映射的非默认构造函数创建Snmp实例,可以添加对特定TransportMapping实例的支持。传输映射用于传入和传出消息。
要为UDP传输设置默认SNMP会话,并支持SNMPv3,可以使用以下代码段:
Address targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
然后如何发送带有身份验证和隐私的同步SNMPv3消息,说明了以下代码片段:
// add user to the USM
snmp.getUSM().addUser(new OctetString("MD5DES"),
new UsmUser(new OctetString("MD5DES"),
AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"),
PrivDES.ID,
new OctetString("MD5DESUserPrivPassword")));
// create the target
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(1);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
// create the PDU
PDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6")));
pdu.setType(PDU.GETNEXT);
// send the PDU
ResponseEvent response = snmp.send(pdu, target);
// extract the response PDU (could be null if timed out)
PDU responsePDU = response.getResponse();
// extract the address used by the agent to send the response:
Address peerAddress = response.getPeerAddress();
异步SNMPv1请求由以下代码发送:
// setting up target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
// creating PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,1})));
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,2})));
pdu.setType(PDU.GETNEXT);
// sending request
ResponseListener listener = new ResponseListener() {
public void onResponse(ResponseEvent event) {
// Always cancel async request when response has been received
// otherwise a memory leak is created! Not canceling a request
// immediately can be useful when sending a request to a broadcast
// address.
((Snmp)event.getSource()).cancel(event.getRequest(), this);
System.out.println("Received response PDU is: "+event.getResponse());
}
};
snmp.sendPDU(pdu, target, null, listener);
通过将以下代码添加到上面的第一个代码段,可以接收陷阱(通知)和其他SNMP PDU:
CommandResponder trapPrinter = new CommandResponder() {
public synchronized void processPdu(CommandResponderEvent e) {
PDU command = e.getPDU();
if (command != null) {
System.out.println(command.toString());
}
}
};
snmp.addCommandResponder(trapPrinter);
代码示例来源:origin: apache/nifi
/**
* Builds target resource.
* @param context Process context
*/
private void buildTargetResource(ProcessContext context) {
if((this.transportMapping == null) || !this.transportMapping.isListening() || (this.snmp == null)) {
try {
this.transportMapping = new DefaultUdpTransportMapping();
this.snmp = new Snmp(this.transportMapping);
if("SNMPv3".equals(context.getProperty(SNMP_VERSION).getValue())) {
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
}
this.transportMapping.listen();
} catch (Exception e) {
throw new IllegalStateException("Failed to initialize UDP transport mapping", e);
}
}
if (this.snmpTarget == null) {
this.snmpTarget = this.createSnmpTarget(context);
}
if (this.targetResource == null) {
this.targetResource = this.finishBuildingTargetResource(context);
}
}
代码示例来源:origin: pentaho/pentaho-kettle
TransportMapping transMap = new DefaultUdpTransportMapping();
snmp = new Snmp( transMap );
transMap.listen();
target.setCommunity( new OctetString( community ) );
target.setVersion( SnmpConstants.version1 );
target.setAddress( udpAddress );
pdu1.setSpecificTrap( PDUv1.ENTERPRISE_SPECIFIC );
pdu1.setEnterprise( new OID( Oid ) );
pdu1.add( new VariableBinding( new OID( Oid ), new OctetString( messageString ) ) );
response = snmp.send( pdu1, target );
new OctetString( passPhrase ) );
USM usm = snmp.getUSM();
response = snmp.send( pdu, usertarget );
try {
if ( snmp != null ) {
snmp.close();
代码示例来源:origin: apache/nifi
/**
* Executes the SNMP set request and returns the response
* @param pdu PDU to send
* @return Response event
* @throws IOException IO Exception
*/
public ResponseEvent set(PDU pdu) throws IOException {
return this.snmp.set(pdu, this.target);
}
代码示例来源:origin: org.jboss.jbossas/jboss-snmp
public static void set(String []oids){
PDU pdu = new PDU();
for (int i = 1; i < oids.length; i+=2){
pdu.add(new VariableBinding(new OID(oids[i]), new OctetString(oids[i+1])));
pdu.setType(PDU.SET);
target.setCommunity(new OctetString("private"));
target.setVersion(SnmpConstants.version2c);
Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
target.setTimeout(1000);
try{
DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
Snmp snmp = new Snmp(transport);
long t1 = System.currentTimeMillis();
System.out.println("SENDING: "+t1);
System.out.println("PDU: " + pdu);
ResponseEvent responseEvent = snmp.set(pdu, target);
long t2=System.currentTimeMillis();
System.out.println("SENT: "+t2);
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws Exception {
// Create PDU
PDU trap = new PDU();
trap.setType(PDU.TRAP);
OID oid = new OID("1.2.3.4.5");
trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid));
trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000))); // put your uptime here
trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));
//Add Payload
Variable var = new OctetString("some string");
trap.add(new VariableBinding(oid, var));
// Specify receiver
Address targetaddress = new UdpAddress("10.101.21.32/162");
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setVersion(SnmpConstants.version2c);
target.setAddress(targetaddress);
// Send
Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.send(trap, target, null, null);
}
代码示例来源:origin: org.opendaylight.cardinal/cardinal-impl
TransportMapping transport = new DefaultUdpTransportMapping();
transport.listen();
comtarget.setCommunity(new OctetString(community));
comtarget.setVersion(snmpVersion);
comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
PDU pdu = new PDU();
Variable var = new OctetString(hostName);
VariableBinding varBind = new VariableBinding(oid, var);
pdu.add(varBind);
pdu.setType(PDU.SET);
pdu.setRequestID(new Integer32(1));
Snmp snmp = new Snmp(transport);
ResponseEvent response = snmp.set(pdu, comtarget);
LOG.info("Error: Agent Timeout... ");
snmp.close();
return true;
代码示例来源:origin: net.itransformers.snmp2xml4j/snmptoolkit
Variable var = new OctetString(value);
VariableBinding vb = new VariableBinding(new OID(this.oid),var);
MessageDispatcher dispatcher = messageDispatcherFactory.createMessageDispatcherMapping();
Snmp snmp = new Snmp(dispatcher, transport);
((MPv3) snmp.getMessageProcessingModel(MPv3.ID)).setLocalEngineID(new OctetString(MPv3.createLocalEngineID()).getValue());
target.setTimeout(timeout);
target.setMaxSizeRequestPDU(65535);
snmp.listen();
logger.debug("SNMP SET TO"+target+" with OID: "+oid+" and value: "+value);
try {
PDU request = new PDU();
request.setType(PDU.SET);
for (int i = 0; i < vbs.size(); i++) {
request.add((VariableBinding) vbs.get(i));
ResponseEvent responseEvent = snmp.set(request, target);
snmp.close();
代码示例来源:origin: org.snmp4j/snmp4j-agent
((Snmp)session).getMessageDispatcher().getTransport(address);
if ((tm != null) && (tm.getListenAddress() instanceof IpAddress)) {
InetAddress localAddress =
pdu = new PDU();
break;
if (mpModel.getValue() != MessageProcessingModel.MPv1) {
if (sysUpTime != null) {
pdu.add(new VariableBinding(SnmpConstants.sysUpTime, sysUpTime));
pdu.add(new VariableBinding(SnmpConstants.sysUpTime,
this.sysUpTime.get()));
? PDU.V1TRAP : PDU.TRAP);
try {
OctetString localEngineID = new OctetString();
OctetString contextEngineID = new OctetString();
if (pdu instanceof ScopedPDU) {
localEngineID.setValue(targetMIB.getLocalEngineID());
contextEngineID = ((ScopedPDU)pdu).getContextEngineID();
代码示例来源:origin: org.kaazing/snmp4j
String logger = (String) ArgumentParser.getValue(parameters, "logger", 0);
if (logger != null) {
OID loggerIndex = new OctetString(logger).toSubIndex(true);
String newLevel = (String) ArgumentParser.getValue(parameters, "level", 0);
levelOID.append(loggerIndex);
int level = LogLevel.toLevel(newLevel).getLevel();
pdu.add(new VariableBinding(levelOID, new Integer32(level)));
ResponseEvent response = snmp.set(pdu, target);
if (response.getResponse() != null) {
switch (response.getResponse().getErrorStatus()) {
case PDU.noError: {
verifyLoggerModification(snmp, target, pdu, levelOID, logger,
pdu.clear();
OID rowStatusOID = new OID(SNMP4J_LOGGER_OIDS[2]);
rowStatusOID.append(loggerIndex);
pdu.add(new VariableBinding(rowStatusOID, new Integer32(4)));
response = snmp.set(pdu, target);
代码示例来源:origin: org.opennms.lib.snmp/org.opennms.lib.snmp.snmp4j
public void registerForTraps(TrapNotificationListener listener, TrapProcessorFactory processorFactory, int snmpTrapPort) throws IOException {
RegistrationInfo info = new RegistrationInfo(listener, snmpTrapPort);
Snmp4JTrapNotifier m_trapHandler = new Snmp4JTrapNotifier(listener, processorFactory);
info.setHandler(m_trapHandler);
TransportMapping transport = new DefaultUdpTransportMapping(new UdpAddress(snmpTrapPort));
info.setTransportMapping(transport);
Snmp snmp = new Snmp(transport);
snmp.addCommandResponder(m_trapHandler);
info.setSession(snmp);
s_registrations.put(listener, info);
snmp.listen();
}
代码示例来源:origin: org.apache.servicemix/servicemix-snmp
@Override
public synchronized void activate() throws Exception {
super.activate();
// load connection data only if the endpoint is enabled
if (isEnabled()) {
logger.debug("Activating endpoint");
this.listenGenericAddress = GenericAddress.parse(this.address);
this.transport = new DefaultUdpTransportMapping((UdpAddress) this.listenGenericAddress);
this.snmp = new Snmp(transport);
snmp.addCommandResponder(this);
}
}
代码示例来源:origin: org.opennms.lib.snmp/org.opennms.lib.snmp.snmp4j
public Snmp createSnmpSession() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp session = new Snmp(transport);
if (isSnmpV3()) {
// Make a new USM
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
// Add the specified user to the USM
usm.addUser(
getSecurityName(),
new UsmUser(
getSecurityName(),
getAuthProtocol(),
getAuthPassPhrase(),
getPrivProtocol(),
getPrivPassPhrase()
)
);
// Remove the old SNMPv3 MessageProcessingModel. If you don't do this, you'll end up with
// two SNMPv3 MessageProcessingModel instances in the dispatcher and connections will fail.
MessageProcessingModel oldModel = session.getMessageDispatcher().getMessageProcessingModel(MessageProcessingModel.MPv3);
if (oldModel != null) {
session.getMessageDispatcher().removeMessageProcessingModel(oldModel);
}
// Add a new SNMPv3 MessageProcessingModel with the newly-created USM
session.getMessageDispatcher().addMessageProcessingModel(new MPv3(usm));
}
return session;
}
代码示例来源:origin: oVirt/ovirt-engine
private org.snmp4j.Snmp createSnmp3(Profile profile) {
try {
TransportMapping<?> transport = new DefaultUdpTransportMapping();
org.snmp4j.Snmp snmp = new org.snmp4j.Snmp(transport);
SecurityProtocols securityProtocols = SecurityProtocols.getInstance();
securityProtocols.addDefaultProtocols();
securityProtocols.addAuthenticationProtocol(new AuthMD5());
securityProtocols.addAuthenticationProtocol(new AuthSHA());
securityProtocols.addPrivacyProtocol(new PrivAES128());
securityProtocols.addPrivacyProtocol(new PrivAES192());
securityProtocols.addPrivacyProtocol(new PrivAES256());
USM usm = new USM(securityProtocols, profile.engineId, 0);
((org.snmp4j.mp.MPv3) snmp.getMessageProcessingModel(org.snmp4j.mp.MPv3.ID))
.setLocalEngineID(profile.engineId.getValue());
((org.snmp4j.mp.MPv3) snmp.getMessageProcessingModel(org.snmp4j.mp.MPv3.ID))
.getSecurityModels().addSecurityModel(usm);
SecurityModels.getInstance().addSecurityModel(
usm);
transport.listen();
snmp.getUSM().addUser(
profile.username,
getUsmUser(profile));
return snmp;
} catch (IOException e) {
throw new NotificationServiceException("error creating version 3 snmp " + getClass().getName());
}
}
代码示例来源:origin: OpenNMS/opennms
public void testGetSysName() throws IOException {
Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.listen();
Address addr = new UdpAddress(InetAddress.getLocalHost(), 9161);
//Address addr = new UdpAddress(InetAddressUtils.addr("192.168.0.100"), 161);
Target target = new CommunityTarget(addr, new OctetString("public"));
target.setVersion(SnmpConstants.version1);
target.setTimeout(3000);
target.setRetries(3);
PDUv1 getRequest = new PDUv1();
getRequest.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0")));
ResponseEvent e = snmp.get(getRequest, target);
PDU response = e.getResponse();
assertEquals(new OctetString("mockhost"), response.get(0).getVariable());
}
代码示例来源:origin: org.opendaylight.cardinal/cardinal-impl
transport = new DefaultTcpTransportMapping((TcpAddress) address);
} else {
transport = new DefaultUdpTransportMapping((UdpAddress) address);
target.setCommunity(new OctetString("public"));
Snmp snmp = new Snmp(mDispathcher, transport);
snmp.addCommandResponder(this);
代码示例来源:origin: fbacchella/jrds
@Override
public final boolean start() {
try {
snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.listen();
} catch (IOException e) {
log(Level.ERROR, e, "Discovery SNMP listener failed to start: %s", e.getMessage());
}
return true;
}
代码示例来源:origin: apache/cloudstack
public SnmpHelper(String address, String community) {
_target = new CommunityTarget();
_target.setCommunity(new OctetString(community));
_target.setVersion(SnmpConstants.version2c);
_target.setAddress(new UdpAddress(address));
try {
_snmp = new Snmp(new DefaultUdpTransportMapping());
} catch (IOException e) {
_snmp = null;
throw new CloudRuntimeException(" Error in crearting snmp object, " + e.getMessage());
}
}
代码示例来源:origin: org.kaazing/snmp4j
private Snmp createSnmpSession() throws IOException {
AbstractTransportMapping transport;
if (address instanceof TcpAddress) {
transport = new DefaultTcpTransportMapping();
}
else {
transport = new DefaultUdpTransportMapping();
}
// Could save some CPU cycles:
// transport.setAsyncMsgProcessingSupported(false);
Snmp snmp = new Snmp(transport);
((MPv3)snmp.getMessageProcessingModel(MPv3.ID)).
setLocalEngineID(localEngineID.getValue());
if (version == SnmpConstants.version3) {
USM usm = new USM(SecurityProtocols.getInstance(),
localEngineID,
engineBootCount);
SecurityModels.getInstance().addSecurityModel(usm);
addUsmUser(snmp);
}
return snmp;
}
代码示例来源:origin: griddynamics/jagger
public ResponseEvent get(List<OID> oids) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
代码示例来源:origin: net.itransformers.snmp2xml4j/snmptoolkit
protected void doInit() {
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
OID authenticationProtocolOID = null;
snmp.getUSM().addUser(new OctetString(ver3Username),
new UsmUser(new OctetString(ver3Username), null, null, null, null));
snmp.getUSM().addUser(new OctetString(ver3Username),
new UsmUser(new OctetString(ver3Username), authenticationProtocolOID, new OctetString(ver3AuthPasscode), null, null));
snmp.getUSM().addUser(new OctetString(ver3Username),
new UsmUser(new OctetString(ver3Username), authenticationProtocolOID, new OctetString(ver3AuthPasscode), privacyProtocolOID, new OctetString(privacyProtocolPassShare)));
内容来源于网络,如有侵权,请联系作者删除!