SNMP4J 源码包中的使用说明
2016-05-23 16:46
344 查看
SNMP4J 是 APACHE 的一个开源项目,为 SNMP 的编程提供了一个很好的框架.支持 SNMPv1, v2c, v3 版本.既可以编写客户端程序,也可以编写服务器端程序.
没有时间翻译它,就直接把它贴了上来.英文很简单,例子都很直观,不看英文直接看代码也没什么问题.
以下是 org.snmp4j 包下的说明
Provides classes and interfaces for creating, sending, and receiving SNMP messages.
The
payload. This package contains three main groups of classes and interfaces:
Classes for SNMP message and target creation
Classes for SNMP message sending (command generation)
Classes for SNMP message dispatching (command responding)
The following UML package diagram illustrates the dependencies between the packages of the core SNMP4J API. Users of the API normally only need to use the
the
The following UML class diagram shows the most important classes of the org.snmp4j package and their relationships (relationships to other packages are not shown):.
appropriate for the SNMP protocol to be used.
For SNMPv1 and SNMPv2c the
information defined by the
For SNMPv3 the
class and provides the following User Based Security Model (USM) user information: security name, security level, security model (i.e. USM), and authoritative engine ID.
A SNMP message consists of the message's payload, the SNMP Protocol Data Unit (PDU) and a message header. Simplified said, in SNMP4J the message header information is represented by
and the PDU is represented by one of the following classes:
Thus, in order to be able to send a SNMP message with SNMP4J, a
have to be created.
SNMPv3 GETBULK PDU
SNMPv1 TRAP PDU ()
SNMPv2c/SNMPv3 INFORM PDU
User Target
To setup a
The transport mapping is used by the SNMP session to send (and receive) SNMP message to a remote systems by using a transport protocol, for example the User Datagram Protocol (UDP).
A SNMP4J
combinations of those SNMP protocol versions can be supported.
With SNMP4J, SNMP messages can be sent synchronously (blocking) and asynchronously (non-blocking). The
does not use an internal thread to process responses on asynchronous and synchronous requests. Nevertheless it uses the receiver threads of the transport mappings to process responses.
Asynchronous responses are returned by calling a callback method on an object instance that implements the
out on behalf of the transport mapping thread that received the response packet from the wire. Thus, if the called method blocks, the delivery of synchronous and asynchronous messages received on the listen port of that transport mapping will be also blocked.
Other transport mapping will not be affected. Blocking can be avoided by either using synchronous messages only or by decoupling the processing within the callback method.
of the
the
the associated
The transport mapping just receives the SNMP mesage as a stream of bytes and forwards the message to associated
uses one instance of the
The
instances. To receive SNMP messages it is thus sufficient to
Create a
Create a
Instantiate a class that implements the
by calling
When a unhandled SNMP message (thus a SNMP message where no corresponding outstanding request exists) is received, then the
of the
that has decoded the SNMP message.
The
The
The following UML class diagram shows the most important classes of the
Prepare a response message as defined in RFC3412 §7.1.
Prepare an outgoing message as defined in RFC3412 §7.1.
This interface is implemented by the message processing model classes for the SNMP versions 1, v2c, and v3:
The TCP transport mapping is implemented by the
Additional transport mappings can be easily added. It is sufficient to implement the
Classes for support of multi-threaded message dispatching. The class
The following UML class diagram shows the classes of the
没有时间翻译它,就直接把它贴了上来.英文很简单,例子都很直观,不看英文直接看代码也没什么问题.
以下是 org.snmp4j 包下的说明
Provides classes and interfaces for creating, sending, and receiving SNMP messages.
The
org.snmp4jclasses are capable of creating, sending, and receiving SNMPv1/v2c/v3 messages. A SNMP message is composed of its message header and its PDU
payload. This package contains three main groups of classes and interfaces:
Classes for SNMP message and target creation
Classes for SNMP message sending (command generation)
Classes for SNMP message dispatching (command responding)
The following UML package diagram illustrates the dependencies between the packages of the core SNMP4J API. Users of the API normally only need to use the
org.snmp4jand
the
org.snmp4j.smipackages directly.
The following UML class diagram shows the most important classes of the org.snmp4j package and their relationships (relationships to other packages are not shown):.
SNMP Messages and Targets
To exchange a SNMP message with a remote system, that system has to be identified, retransmission, and timeout policy information about the message exchange has to be specified. A remote system is specified with SNMP4J by creating aTargetinstance
appropriate for the SNMP protocol to be used.
For SNMPv1 and SNMPv2c the
CommunityTargethas to be used which provides community information in addition to the address, retransmission, and timeout policy
information defined by the
Targetinterface.
For SNMPv3 the
UserTargethas to be used instead. It extends the
SecureTargetabstract
class and provides the following User Based Security Model (USM) user information: security name, security level, security model (i.e. USM), and authoritative engine ID.
A SNMP message consists of the message's payload, the SNMP Protocol Data Unit (PDU) and a message header. Simplified said, in SNMP4J the message header information is represented by
Targetinstances
and the PDU is represented by one of the following classes:
PDUv1(SNMPv1)
PDU(SNMPv2c)
ScopedPDU(SNMPv3)
Thus, in order to be able to send a SNMP message with SNMP4J, a
PDUinstance and a
Targetinstance
have to be created.
PDU Examples (PDU 使用的例子)
SNMPv1/v2c GETNEXT PDUimport org.snmp4j.PDU; import org.snmp4j.smi.*; ... PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1"))); // sysDescr pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.1"))); // ifNumber pdu.setType(PDU.GETNEXT); ...
SNMPv3 GETBULK PDU
import org.snmp4j.ScopedPDU; import org.snmp4j.smi.*; ... ScopedPDU pdu = new ScopedPDU(); pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.1"))); // ifNumber pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.10"))); // ifInOctets pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.16"))); // ifOutOctets pdu.setType(PDU.GETBULK); pdu.setMaxRepetitions(50); // Get ifNumber only once pdu.setNonRepeaters(1); // set context non-default context (default context does not need to be set) pdu.setContextName(new OctetString("subSystemContextA")); // set non-default context engine ID (to use targets authoritative engine ID // use an empty (size == 0) octet string) pdu.setContextEngineID(OctetString.fromHexString("80:00:13:70:c0:a8:01:0d")); ...
SNMPv1 TRAP PDU ()
import org.snmp4j.PDUv1; ... PDUv1 pdu = new PDUv1(); pdu.setType(PDU.V1TRAP); pdu.setGenericTrap(PDUv1.COLDSTART); ...
SNMPv2c/SNMPv3 INFORM PDU
import org.snmp4j.ScopedPDU; ... ScopedPDU pdu = new ScopedPDU(); pdu.setType(PDU.INFORM); // sysUpTime long sysUpTime = (System.currentTimeMillis() - startTime) / 10; pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(sysUpTime))); pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, SnmpConstants.linkDown)); // payload pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.1"+downIndex), new Integer32(downIndex))); ...
Target Examples (对象例子)
Community TargetCommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString("public")); target.setAddress(targetAddress); target.setVersion(SnmpConstants.version1);
User Target
UserTarget target = new UserTarget(); target.setAddress(targetAddress); target.setRetries(1); // set timeout to 500 milliseconds -> 2*500ms = 1s total timeout target.setTimeout(500); target.setVersion(SnmpConstants.version3); target.setSecurityLevel(SecurityLevel.AUTH_PRIV); target.setSecurityName(new OctetString("MD5DES"));
Sending SNMP messages
SNMP message are sent with SNMP4J by using a instance of the SNMPSessioninterface. The default implementation of this interface is the
Snmpclass.
To setup a
Snmpinstance it is sufficient to call its constructor with a
TransportMappinginstance.
The transport mapping is used by the SNMP session to send (and receive) SNMP message to a remote systems by using a transport protocol, for example the User Datagram Protocol (UDP).
A SNMP4J
Snmpinstance supports SNMP v1, v2c, and v3 by default. By sub-classing
Snmpother
combinations of those SNMP protocol versions can be supported.
With SNMP4J, SNMP messages can be sent synchronously (blocking) and asynchronously (non-blocking). The
Snmpclass
does not use an internal thread to process responses on asynchronous and synchronous requests. Nevertheless it uses the receiver threads of the transport mappings to process responses.
Asynchronous responses are returned by calling a callback method on an object instance that implements the
ResponseListenerinterface. The callback is carried
out on behalf of the transport mapping thread that received the response packet from the wire. Thus, if the called method blocks, the delivery of synchronous and asynchronous messages received on the listen port of that transport mapping will be also blocked.
Other transport mapping will not be affected. Blocking can be avoided by either using synchronous messages only or by decoupling the processing within the callback method.
Example for Sending a Synchronous Message (发送同步消息)
import org.snmp4j.*; ... Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); ... ResponseEvent response = snmp.send(requestPDU, target); if (response.getResponse() == null) { // request timed out ... } else { System.out.println("Received response from: "+ response.getPeerAddress()); // dump response PDU System.out.println(response.getResponse().toString()); }
Example for Sending an Asynchronous Message (发送异步消息)
import org.snmp4j.*; import org.snmp4j.event.*; ... Snmp snmp = new Snmp(new DefaultUdpTransportMapping()); ... ResponseListener listener = new ResponseListener() { public void onResponse(ResponseEvent event) { PDU response = event.getResponse(); PDU request = event.getRequest(); if (response == null) { System.out.println("Request "+request+" timed out"); } else { System.out.println("Received response "+response+" on request "+ request); } }; snmp.sendPDU(request, target, null, listener); ...
Receiving SNMP messages(接收SNMP信息)
SNMP4J receives SNMP messages through the listen port of transport mappings. In order to be able to receive responses or requests, that port needs to be set into listen mode. This has to be done by calling thelisten()method
of the
TransportMappinginstance to start the transport mappings internal listen thread. The internal thread is stopped and the listen port is closed by calling
the
close()method on the
TransportMappinginstance or
the associated
Snmpinstance.
The transport mapping just receives the SNMP mesage as a stream of bytes and forwards the message to associated
MessageDispatcherinstances. By default, SNMP4J
uses one instance of the
MessageDispatcherImplclass for decoding and dispatching incoming messages. That instance is created and used internally by the
Snmpclass.
The
Snmpclass processes responses to outstanding requests and forwards PDUs of other SNMP messages to registered
CommandResponderlistener
instances. To receive SNMP messages it is thus sufficient to
Create a
TransportMappingand initialize its listen port by calling
TransportMapping.listen().
Create a
Snmpinstance with the above
TransportMapping.
Instantiate a class that implements the
CommandResponderinterface and register it with the
Snmpinstance
by calling
Snmp.addCommandResponder(CommandResponder).
When a unhandled SNMP message (thus a SNMP message where no corresponding outstanding request exists) is received, then the
processPdu(CommandResponderEvent)method
of the
CommandResponderwill be called with the decoded PDU and additional information about the received SNMP message provided by the message processing model
that has decoded the SNMP message.
Example for Receiving SNMP Messages (接收SNMP消息的例子)
import org.snmp4j.*; import org.snmp4j.smi.*; import org.snmp4j.mp.SnmpConstants; ... TransportMapping transport = new DefaultUdpTransportMapping(new UdpAddress("0.0.0.0/161")); Snmp snmp = new Snmp(transport); if (version == SnmpConstants.version3) { byte[] localEngineID = ((MPv3)snmp.getMessageProcessingModel(MessageProcessingModel.MPv3)).createLocalEngineID(); USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(localEngineID), 0); SecurityModels.getInstance().addSecurityModel(usm); snmp.setLocalEngine(localEngineID, 0, 0); // Add the configured user to the USM ... } snmp.addCommandResponder(this); transport.listen(); ... public synchronized void processPdu(CommandResponderEvent e) { PDU command = e.getPdu(); if (command != null) { ... } }
以下是 org.snmp4j.smi 包下的说明:
Provides classes for the representation of SMIv1/v2 data types (which also includes some basic ASN.1 primitive data types).The
org.snmp4j.smiclasses are capable of BER encoding and decoding themself to/from a byte stream. In addition, the SMI data type classes provide convenient functions for manipulating their content. The
VariantVariableis a special class that can be used in command responder applications to intercept access to a SMI value.
Variable Binding Examples
import org.snmp4j.smi.*; ... VariableBinding vb = new VariableBinding(new OID("1.3.6.1.2.1.1.4.0")); vb.setValue(new OctetString("SNMP4J Text")); ... vb = new VariableBinding(); vb.setOid(new OID(new int[] { 1,3,6,1,2,1,1,2,0 })); ... vb = new VariableBinding(vb.getOid(), new IpAddress("255.255.255.255")); ... vb = new VariableBinding(vb.getOid(), new Gauge32(2^32-1)); int syntax = vb.getSyntax(); if (syntax != SMIConstants.SYNTAX_GAUGE32) { // never reached } else { long value = ((UnsignedInteger32)vb.getValue()).getValue(); System.out.println(vb.getOid() + " = " + value); // prints: 1.3.6.1.2.1.1.2.0 = 4294967295 } ...The following UML class diagram shows the most important classes of the
org.snmp4j.smipackage and their relationships (relationships to other packages are not shown): UML类图
以下是 org.snmp.asn1 包中的说明
Provides classes and interfaces for the mapping between Abstract Syntax Notation One (ASN.1) formatted values and their transfer syntax according to the Basic Encoding Rules (BER).The
org.snmp4j.asn1classes are capable of serializing of ASN.1 formatted values into a byte stream and deserializing the same from a byte stream. There are three groups of classes/interfaces in this package: The
BERclass implements the BER serialization and deserialization by providing static methods for encoding/decoding of primitive ASN.1 and Structure of Management Information (SMI) data types.
The
BERSerializableinterface provides a common interface for all objects that are (de)serializable according to the Basic Encoding Rules (BER).
The
BERInputStreamand the
BEROutputStreamprovide optimized implementations for the serialization and deserialization of the
InputStreamand
OutputStreamabstract classes.
The following UML class diagram shows the most important classes of the
org.snmp4j.asn1package and their relationships (relationships to other packages are not shown): 以下是 org.snmp4j.mp 包中的说明
Provides classes and interfaces for the SNMP message processing.The
org.snmp4j.mpclasses provide services to process SNMP messages. The services provided are defined in the
MessageProcessingModelinterface and include the following: Prepare data elements from an incoming SNMP message as described in RFC3412 §7.2.
Prepare a response message as defined in RFC3412 §7.1.
Prepare an outgoing message as defined in RFC3412 §7.1.
This interface is implemented by the message processing model classes for the SNMP versions 1, v2c, and v3:
MPv1,
MPv2c, and
MPv3. The
MessageDispatcherImplchooses which message processing model it uses to process an outgoing or incoming SNMP message based on the SNMP version of the message. The SNMP version is either extracted from the message header (incoming message) or from the
Targetinstance associated with the outgoing PDU (ougoing message). To be able to match requests and responses SNMP uses request IDs. Since request IDs are created by the command generator, the request IDs are unique within such a command generator only. SNMP4J therefore has to abstract from request IDs and uses
PduHandleinstances instead. If a
PDUis processed for sending by the SNMP4J
MessageDispatcherImpland the PDU's request ID is set to 0, then a SNMP4J application wide unique ID is generated and set as request ID of the supplied PDU. In any case, the PDU's request ID will be used as transaction ID of the outgoing message. The transaction ID identifies a messages
PduHandle. If a
PDUis received by the SNMP4J
MessageDispatcherImpla unique transaction ID is generated so that command responders as well as the message processing model can match requests and responses. The following UML class diagram shows the most important classes of the
org.snmp4j.mppackage and their relationships (relationships to other packages are not shown): 以下是 org.snmp4j.transport 包中的说明
Provides transport protocol mappings for SNMP.The
org.snmp4j.transportclasses are capable of sending and receiving byte messages to and from a network using transport mapping specific transport protocol. All SNMP4J transport mappings have to implement the
org.snmp4j.TransportMappinginterface. SNMP4J supports two transport mappings for the transport protocols UDP and TCP: The UDP transport mapping is the default SNMP transport mapping. It is implemented by the
DefaultUdpTransportMappingclass.
The TCP transport mapping is implemented by the
DefaultTcpTransportMappingusing the
java.niopackage.
Additional transport mappings can be easily added. It is sufficient to implement the
org.snmp4j.TransportMappinginterface and add an instance of that class to the
Snmp(or
MessageDispatcher) object. To be able to lookup a transport mapping by an
Addressclass via the
TransportMappings(as
Snmpdoes for notification listeners), a transport mapping has to be registered in a transport mapping registration file. The default file is
transports.propertiesin the
org.snmp4j.transportpackage. To use a different file, set the system property
org.snmp4j.transportMappings. Connection-oriented transport mappings like TCP should implement the
ConnectionOrientedTransportMappinginterface to support
MessageLengthDecoderand
TransportStateListener.The following UML class diagram shows the classes of the
org.snmp4j.transportpackage and their relationships (relationships to other packages are not shown): 以下是 org.snmp4j.util 包中的说明
Contains table retrieval utilities and multi-threading support classes as well as miscellaneous utility classes.The
org.snmp4j.utilcontains the following groups of classes: Classes for SNMP table retrieval. The class
TableUtilscan be used to asynchronously retrieve table data effeciently row by row.
Classes for support of multi-threaded message dispatching. The class
MultiThreadedMessageDispatcherimplements the
MessageDispatcherinterface and uses the
MessageDispatcherImplclass to dispatch incoming message using the threads of a
ThreadPool.
The following UML class diagram shows the classes of the
org.snmp4j.utilpackage and their relationships (relationships to other packages are not shown): 在 SNMP4J 包中还有多线程的东东,主要用于服务器端.文档里没写,去看 API 吧,里面有绍.
相关文章推荐
- hdu 5690 All X
- Web/HTTP 调试利器(Fiddler)
- Thinking in java 之 内部类
- Java Arrys的用法
- NSDictionary的使用及常用方法(如实始化、添加元素、删除元素、修改元素值等)
- Fiddler(Web/HTTP调试利器)
- 专题:链表结点的删除
- 工作漏洞总结
- oracle返回多个参数
- zookeeper 管理 项目配置文件
- 字典树...(eg.hdu 1251)
- (版本定制)第12课:Spark Streaming源码解读之Executor容错安全性
- demo_音乐播放器_Service
- NavigationBar
- centos删除自带的openjdk并安装sun公司的jdk
- Xcode真机调试中的 "The Developer Disk Image could not be mounted." 问题
- 开始学习语音识别技术
- HTML5引入的新数组TypedArray介绍
- 《Head first in Java学习总结与收获》
- Android网络编程(六)OkHttp3用法全解析