📄 java.txt
字号:
package snmpexamples;
import java.io.IOException;
import java.util.Vector;
import org.apache.log4j.*;
import org.snmp4j.*;
import org.snmp4j.mp.*;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.*;
import org.snmp4j.util.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.tools.console.SnmpRequest;
import java.util.StringTokenizer;
import org.snmp4j.log.LogFactory;
import org.snmp4j.log.Log4jLogFactory;
import org.snmp4j.asn1.BER;
/**
* The SnmpRequest application is an example implementation of most of the
* SNMP4J features. It can be used to send SNMP requests to a target or to
* listen for traps/notifications and inform requests.
*
* @author Frank Fock
* @version 1.0.3
* @since 1.0
*/
public class Application1 implements CommandResponder, PDUFactory {
// initialize Log4J logging
static {
LogFactory.setLogFactory(new Log4jLogFactory());
BER.setCheckSequenceLength(false);
}
public static final int DEFAULT = 0;
public static final int WALK = 1;
public static final int LISTEN = 2;
public static final int TABLE = 3;
public static final int CVS_TABLE = 4;
public static final int TIME_BASED_CVS_TABLE = 5;
Target target;
Address address=new UdpAddress("172.17.246.9/161");
OID authProtocol;
OID privProtocol;
OctetString privPassphrase;
OctetString authPassphrase;
OctetString community = new OctetString("public");
OctetString authoritativeEngineID;
OctetString contextEngineID;
OctetString contextName = new OctetString();
OctetString securityName = new OctetString();
TimeTicks sysUpTime = new TimeTicks(0);
OID trapOID = SnmpConstants.coldStart;
PDUv1 v1TrapPDU = new PDUv1();
int version = SnmpConstants.version3;
int retries = 1;
int timeout = 1000;
int pduType = PDU.GETNEXT;
int maxRepetitions = 10;
int nonRepeaters = 0;
Vector vbs = new Vector();
protected int operation = DEFAULT;
int numDispatcherThreads = 2;
boolean useDenseTableOperation = false;
// table options
OID lowerBoundIndex, upperBoundIndex;
public Application1(String[] args) {
// Set the default counter listener to return proper USM and MP error
// counters.
CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
System.out.println(vbs);
vbs.add(new VariableBinding(new OID("1.3.6.1.4.1.9")));
System.out.println(vbs);
int paramStart = parseArgs(args);
if (paramStart >= args.length) {
//printUsage(); //程序走到这就停住了
//System.exit(1);
}
else {
checkOptions();
address = getAddress(args[paramStart++]);
Vector vbs = getVariableBindings(args, paramStart);
checkTrapVariables(vbs);
if (vbs.size() > 0) {
this.vbs = vbs;
}
}
}
public int getPduType() {
return pduType;
}
public int getVersion() {
return version;
}
public Vector getVbs() {
return vbs;
}
public boolean isUseDenseTableOperation() {
return useDenseTableOperation;
}
public OID getUpperBoundIndex() {
return upperBoundIndex;
}
public OID getTrapOID() {
return trapOID;
}
public int getTimeout() {
return timeout;
}
public Target getTarget() {
return target;
}
public TimeTicks getSysUpTime() {
return sysUpTime;
}
public OctetString getSecurityName() {
return securityName;
}
public int getRetries() {
return retries;
}
public OID getPrivProtocol() {
return privProtocol;
}
public OctetString getPrivPassphrase() {
return privPassphrase;
}
public int getOperation() {
return operation;
}
public int getNumDispatcherThreads() {
return numDispatcherThreads;
}
public int getNonRepeaters() {
return nonRepeaters;
}
public int getMaxRepetitions() {
return maxRepetitions;
}
public OID getLowerBoundIndex() {
return lowerBoundIndex;
}
public OctetString getContextName() {
return contextName;
}
public OctetString getContextEngineID() {
return contextEngineID;
}
public OctetString getCommunity() {
return community;
}
public OctetString getAuthoritativeEngineID() {
return authoritativeEngineID;
}
public OID getAuthProtocol() {
return authProtocol;
}
public OctetString getAuthPassphrase() {
return authPassphrase;
}
public Address getAddress() {
return address;
}
private void checkOptions() {
if ((operation == WALK) &&
((pduType != PDU.GETBULK) && (pduType != PDU.GETNEXT))) {
throw new IllegalArgumentException(
"Walk operation is not supported for PDU type: "+
PDU.getTypeString(pduType));
}
else if ((operation == WALK) && (vbs.size() != 1)) {
throw new IllegalArgumentException(
"There must be exactly one OID supplied for walk operations");
}
if ((pduType == PDU.V1TRAP) && (version != SnmpConstants.version1)) {
throw new IllegalArgumentException(
"V1TRAP PDU type is only available for SNMP version 1");
}
}
private void checkTrapVariables(Vector vbs) {
if ((pduType == PDU.INFORM) ||
(pduType == PDU.TRAP)) {
if ((vbs.size() == 0) ||
((vbs.size() > 1) &&
(!((VariableBinding) vbs.get(0)).getOid().equals(SnmpConstants.
sysUpTime)))) {
vbs.add(0, new VariableBinding(SnmpConstants.sysUpTime, sysUpTime));
}
if ((vbs.size() == 1) ||
((vbs.size() > 2) &&
(!((VariableBinding) vbs.get(1)).getOid().equals(SnmpConstants.
snmpTrapOID)))) {
vbs.add(1, new VariableBinding(SnmpConstants.snmpTrapOID, trapOID));
}
}
}
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());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
Snmp snmp = new Snmp(mtDispatcher, transport);
if (version == SnmpConstants.version3) {
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
if (authoritativeEngineID != null) {
snmp.setLocalEngine(authoritativeEngineID.getValue(), 0, 0);
}
// Add the configured user to the USM
addUsmUser(snmp);
}
else {
CommunityTarget target = new CommunityTarget();
target.setCommunity(community);
this.target = target;
}
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on "+address);
try {
this.wait();
}
catch (InterruptedException ex) {
}
}
private void addUsmUser(Snmp snmp) {
snmp.getUSM().addUser(securityName, new UsmUser(securityName,
authProtocol,
authPassphrase,
privProtocol,
privPassphrase));
}
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);
if (version == SnmpConstants.version3) {
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
addUsmUser(snmp);
}
return snmp;
}
private Target createTarget() {
if (version== SnmpConstants.version3) {
UserTarget target = new UserTarget();
if (authPassphrase != null) {
if (privPassphrase != null) {
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
}
else {
target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
}
}
else {
target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
}
target.setSecurityName(securityName);
return target;
}
else {
CommunityTarget target = new CommunityTarget();
target.setCommunity(community);
return target;
}
}
public PDU send() throws IOException {
Snmp snmp = createSnmpSession();
//this.target = createTarget();
System.out.println("create target..");
CommunityTarget t= new CommunityTarget();
t.setCommunity(community);
System.out.println(community);
this.target = t;
target.setVersion(version);
target.setAddress(address);
target.setRetries(retries);
target.setTimeout(timeout);
snmp.listen();
System.out.println("listen..");
PDU request = createPDU(target);
if (request.getType() == PDU.GETBULK) {
request.setMaxRepetitions(maxRepetitions);
request.setNonRepeaters(nonRepeaters);
}
//request.add(new VariableBinding(new OID("1.3.6.1.2.1")));
for (int i=0; i<vbs.size(); i++) {
request.add((VariableBinding)vbs.get(i));
System.out.print(vbs.get(i));
System.out.println();
}
System.out.println(vbs);
PDU response = null;
//response = walk(snmp, request, target);
if (operation == WALK) {
response = walk(snmp, request, target);
}
else {
ResponseEvent responseEvent;
long startTime = System.currentTimeMillis();
responseEvent = snmp.send(request, target);
System.out.println("request: "+responseEvent.getRequest());
System.out.println("wait response..");
if (responseEvent != null) {
response = responseEvent.getResponse();
System.out.println(response);
System.out.println(" "+responseEvent.getRequest());
System.out.println("Received response after "+
(System.currentTimeMillis()-startTime)+" millis");
}
}
snmp.close();
return response;
}
private static PDU walk(Snmp snmp, PDU request, Target target) throws IOException {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -