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

📄 snmprequest.java

📁 snmp4j 1.8.2版 The org.snmp4j classes are capable of creating, sending, and receiving SNMPv1/v2c/v3
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
      if (contextEngineID != null) {
        scopedPDU.setContextEngineID(contextEngineID);
      }
      if (contextName != null) {
        scopedPDU.setContextName(contextName);
      }
    }
    else {
      if (pduType == PDU.V1TRAP) {
        request = v1TrapPDU;
      }
      else {
        request = new PDU();
      }
    }
    request.setType(pduType);
    return request;
  }

  public void table() throws IOException {
    Snmp snmp = createSnmpSession();
    this.target = createTarget();
    target.setVersion(version);
    target.setAddress(address);
    target.setRetries(retries);
    target.setTimeout(timeout);
    snmp.listen();

    TableUtils tableUtils = new TableUtils(snmp, this);
    tableUtils.setMaxNumRowsPerPDU(maxRepetitions);
    Counter32 counter = new Counter32();

    OID[] columns = new OID[vbs.size()];
    for (int i=0; i<columns.length; i++) {
      columns[i] = ((VariableBinding)vbs.get(i)).getOid();
    }
    long startTime = System.currentTimeMillis();
    synchronized (counter) {

      TableListener listener;
      if (operation == TABLE) {
        listener = new TextTableListener();
      }
      else {
        listener = new CVSTableListener(System.currentTimeMillis());
      }
      if (useDenseTableOperation) {
        tableUtils.getDenseTable(target, columns, listener, counter,
                                 lowerBoundIndex, upperBoundIndex);
      }
      else {
        tableUtils.getTable(target, columns, listener, counter,
                            lowerBoundIndex, upperBoundIndex);
      }
      try {
        counter.wait(timeout);
      }
      catch (InterruptedException ex) {
      }
    }
    System.out.println("Table received in "+
                       (System.currentTimeMillis()-startTime)+" milliseconds.");
    snmp.close();
  }

  class CVSTableListener implements TableListener {

    private long requestTime;

    public CVSTableListener(long time) {
      this.requestTime = time;
    }

    public boolean next(TableEvent event) {
      if (operation == TIME_BASED_CVS_TABLE) {
        System.out.print(requestTime);
        System.out.print(",");
      }
      System.out.print("\""+event.getIndex()+"\",");
      for (int i=0; i<event.getColumns().length; i++) {
        Variable v = event.getColumns()[i].getVariable();
        String value = v.toString();
        switch (v.getSyntax()) {
          case SMIConstants.SYNTAX_OCTET_STRING: {
            StringBuffer escapedString = new StringBuffer(value.length());
            StringTokenizer st = new StringTokenizer(value, "\"", true);
            while (st.hasMoreTokens()) {
              String token = st.nextToken();
              escapedString.append(token);
              if (token.equals("\"")) {
                escapedString.append("\"");
              }
            }
          }
          case SMIConstants.SYNTAX_IPADDRESS:
          case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
          case SMIConstants.SYNTAX_OPAQUE: {
            System.out.print("\"");
            System.out.print(value);
            System.out.print("\"");
            break;
          }
          default: {
            System.out.print(value);
          }
        }
        if (i+1 < event.getColumns().length) {
          System.out.print(",");
        }
      }
      System.out.println();
      return true;
    }

    public void finished(TableEvent event) {
      synchronized (event.getUserObject()) {
        event.getUserObject().notify();
      }
    }

  }

  class TextTableListener implements TableListener {

    public void finished(TableEvent event) {
      System.out.println();
      System.out.println("Table walk completed with status "+event.getStatus()+
                         ". Received "+
                         event.getUserObject()+" rows.");
      synchronized (event.getUserObject()) {
        event.getUserObject().notify();
      }
    }

    public boolean next(TableEvent event) {
      System.out.println("Index = "+event.getIndex()+":");
      for (int i=0; i<event.getColumns().length; i++) {
        System.out.println(event.getColumns()[i]);
      }
      System.out.println();
      ((Counter32)event.getUserObject()).increment();
      return true;
    }

  }

  public static void main(String[] args) {
    try {
/* Initialize Log4J logging:
      if (System.getProperty("log4j.configuration") == null) {
        BasicConfigurator.configure();
      }
      Logger.getRootLogger().setLevel(Level.OFF);
*/
      SnmpRequest snmpRequest = new SnmpRequest(args);
      try {
        if (snmpRequest.operation == LISTEN) {
          snmpRequest.listen();
        }
        else if ((snmpRequest.operation == TABLE) ||
                 (snmpRequest.operation == CVS_TABLE) ||
                 (snmpRequest.operation == TIME_BASED_CVS_TABLE)) {
          snmpRequest.table();
        }
        else {
          PDU response = snmpRequest.send();
          if ((snmpRequest.getPduType() == PDU.TRAP) ||
              (snmpRequest.getPduType() == PDU.REPORT) ||
              (snmpRequest.getPduType() == PDU.V1TRAP) ||
              (snmpRequest.getPduType() == PDU.RESPONSE)) {
            System.out.println(PDU.getTypeString(snmpRequest.getPduType()) +
                               " sent successfully");
          }
          else if (response == null) {
            if (snmpRequest.operation != WALK) {
              System.out.println("Request timed out.");
            }
          }
          else if (response.getType() == PDU.REPORT)
          {
            printReport(response);
          }
          else if (snmpRequest.operation == DEFAULT)
          {
            System.out.println("Response received with requestID=" +
                               response.getRequestID() +
                               ", errorIndex=" +
                               response.getErrorIndex() + ", " +
                               "errorStatus=" + response.getErrorStatusText()+
                               "("+response.getErrorStatus()+")");
            printVariableBindings(response);
          }
          else
          {
            System.out.println("Received something strange: requestID=" +
                               response.getRequestID() +
                               ", errorIndex=" +
                               response.getErrorIndex() + ", " +
                               "errorStatus=" + response.getErrorStatusText()+
                               "("+response.getErrorStatus()+")");
            printVariableBindings(response);
          }
        }
      }
      catch (IOException ex) {
        System.err.println("Error while trying to send request: " +
                           ex.getMessage());
        ex.printStackTrace();
      }
    }
    catch (IllegalArgumentException iaex) {
      System.err.print("Error: "+iaex.getMessage());
      iaex.printStackTrace();
    }
  }

  public void setAddress(Address address) {
    this.address = address;
  }

  public void setVersion(int version) {
    this.version = version;
  }

  public void setVbs(Vector vbs) {
    this.vbs = vbs;
  }

  public void setUseDenseTableOperation(boolean useDenseTableOperation) {
    this.useDenseTableOperation = useDenseTableOperation;
  }

  public void setUpperBoundIndex(OID upperBoundIndex) {
    this.upperBoundIndex = upperBoundIndex;
  }

  public void setTrapOID(OID trapOID) {
    this.trapOID = trapOID;
  }

  public void setTimeout(int timeout) {
    this.timeout = timeout;
  }

  public void setTarget(Target target) {
    this.target = target;
  }

  public void setSysUpTime(TimeTicks sysUpTime) {
    this.sysUpTime = sysUpTime;
  }

  public void setSecurityName(OctetString securityName) {
    this.securityName = securityName;
  }

  public void setRetries(int retries) {
    this.retries = retries;
  }

  public void setPrivProtocol(OID privProtocol) {
    this.privProtocol = privProtocol;
  }

  public void setPrivPassphrase(OctetString privPassphrase) {
    this.privPassphrase = privPassphrase;
  }

  public void setPduType(int pduType) {
    this.pduType = pduType;
  }

  public void setOperation(int operation) {
    this.operation = operation;
  }

  public void setNumDispatcherThreads(int numDispatcherThreads) {
    this.numDispatcherThreads = numDispatcherThreads;
  }

  public void setNonRepeaters(int nonRepeaters) {
    this.nonRepeaters = nonRepeaters;
  }

  public void setMaxRepetitions(int maxRepetitions) {
    this.maxRepetitions = maxRepetitions;
  }

  public void setLowerBoundIndex(OID lowerBoundIndex) {
    this.lowerBoundIndex = lowerBoundIndex;
  }

  public void setContextName(OctetString contextName) {
    this.contextName = contextName;
  }

  public void setContextEngineID(OctetString contextEngineID) {
    this.contextEngineID = contextEngineID;
  }

  public void setCommunity(OctetString community) {
    this.community = community;
  }

  public void setAuthoritativeEngineID(OctetString authoritativeEngineID) {
    this.authoritativeEngineID = authoritativeEngineID;
  }

  public void setAuthProtocol(OID authProtocol) {
    this.authProtocol = authProtocol;
  }

  public void setAuthPassphrase(OctetString authPassphrase) {
    this.authPassphrase = authPassphrase;
  }

  class WalkCounts {
    public int requests;
    public int objects;
  }
}

⌨️ 快捷键说明

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