⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmprequest.java

📁 snmp4j 1.8.2版 The org.snmp4j classes are capable of creating, sending, and receiving SNMPv1/v2c/v3
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/*_############################################################################
  _##
  _##  SNMP4J - SnmpRequest.java
  _##
  _##  Copyright 2003-2007  Frank Fock and Jochen Katz (SNMP4J.org)
  _##
  _##  Licensed under the Apache License, Version 2.0 (the "License");
  _##  you may not use this file except in compliance with the License.
  _##  You may obtain a copy of the License at
  _##
  _##      http://www.apache.org/licenses/LICENSE-2.0
  _##
  _##  Unless required by applicable law or agreed to in writing, software
  _##  distributed under the License is distributed on an "AS IS" BASIS,
  _##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  _##  See the License for the specific language governing permissions and
  _##  limitations under the License.
  _##
  _##########################################################################*/

package org.snmp4j.tools.console;

import java.io.IOException;
import java.util.Vector;
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 java.util.StringTokenizer;
import org.snmp4j.log.LogFactory;
import org.snmp4j.asn1.BER;
import org.snmp4j.log.JavaLogFactory;
import org.snmp4j.log.LogLevel;

/**
 * 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.8
 */
public class SnmpRequest implements CommandResponder, PDUFactory {

  // initialize Java logging
  static {
    LogFactory.setLogFactory(new JavaLogFactory());
    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;
  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();
  OctetString localEngineID = new OctetString(MPv3.createLocalEngineID());

  TimeTicks sysUpTime = new TimeTicks(0);
  OID trapOID = SnmpConstants.coldStart;

  PDUv1 v1TrapPDU = new PDUv1();

  int version = SnmpConstants.version3;
  int engineBootCount = 0;
  int retries = 1;
  int timeout = 1000;
  int pduType = PDU.GETNEXT;
  int maxRepetitions = 10;
  int nonRepeaters = 0;
  int maxSizeResponsePDU = 65535;
  Vector vbs = new Vector();

  protected int operation = DEFAULT;

  int numDispatcherThreads = 2;

  boolean useDenseTableOperation = false;

  // table options
  OID lowerBoundIndex, upperBoundIndex;


  public SnmpRequest(String[] args) {
    // Set the default counter listener to return proper USM and MP error
    // counters.
    CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());

    vbs.add(new VariableBinding(new OID("1.3.6")));
    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(), localEngineID, 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);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -