Example #1
0
  private void requestAndVerifyResponse(int pduType, int version) throws Exception {
    PDU pdu = createPDU(version);

    for (AnticipatedRequest a : m_requestedVarbinds) {
      pdu.add(a.getRequestVarbind());
    }
    pdu.setType(pduType);

    PDU response = sendRequest(pdu, version);

    assertNotNull("request timed out", response);
    System.err.println("Response is: " + response);
    assertTrue(
        "unexpected report pdu: "
            + ((VariableBinding) response.getVariableBindings().get(0)).getOid(),
        response.getType() != PDU.REPORT);

    assertEquals(
        "Unexpected number of varbinds returned.",
        m_requestedVarbinds.size(),
        response.getVariableBindings().size());

    for (int i = 0; i < m_requestedVarbinds.size(); i++) {
      AnticipatedRequest a = m_requestedVarbinds.get(i);
      VariableBinding vb = response.get(i);
      a.verify(vb);
    }

    reset();
  }
 public String snmpGet(String strAddress, String community, String strOID) // SNMPget
     {
   String str = "";
   try {
     OctetString community1 = new OctetString(community);
     strAddress = strAddress + "/" + 161; // Direccion + Puerto SNMP
     Address targetaddress = new UdpAddress(strAddress); // direccion con puerto
     TransportMapping transport = new DefaultUdpTransportMapping();
     transport.listen();
     /*
      * Este metodo regresa un Target, que contiene informacion acerca de los
      * datos y como deben ser mostrados y sus rangos.
      */
     CommunityTarget comtarget = new CommunityTarget();
     comtarget.setCommunity(community1);
     comtarget.setVersion(SnmpConstants.version1);
     comtarget.setAddress(targetaddress);
     comtarget.setRetries(2);
     comtarget.setTimeout(5000);
     PDU pdu = new PDU();
     ResponseEvent response;
     Snmp snmp;
     pdu.add(new VariableBinding(new OID(strOID)));
     pdu.setType(PDU.GET);
     snmp = new Snmp(transport);
     response = snmp.get(pdu, comtarget);
     if (response != null) {
       if (response.getResponse().getErrorStatusText().equalsIgnoreCase("Success")) {
         PDU pduresponse = response.getResponse();
         str = pduresponse.getVariableBindings().firstElement().toString();
         if (str.contains("=")) {
           int len = str.indexOf("=");
           str = str.substring(len + 1, str.length());
         }
       }
     } else {
       System.out.println("Feeling like a TimeOut occured ");
     }
     // En caso de que ocurra un Time out
     snmp.close(); // cierra conexión
   } catch (Exception e) {
   }
   System.out.println("Response= " + str); // en caso de ocurrio error lo arroja
   return str;
 }
Example #3
0
 @Override
 public void onResponse(ResponseEvent event) {
   SnmpUriResponse response = new SnmpUriResponse(SnmpUriResponse.Type.TIMEOUT);
   PDU responsePDU = event.getResponse();
   if (responsePDU != null) {
     if (responsePDU.getErrorStatus() != PDU.noError) {
       response = new SnmpUriResponse(responsePDU.getErrorStatus());
     } else {
       response =
           new SnmpUriResponse(
               Collections.singletonList(
                   responsePDU
                       .getVariableBindings()
                       .toArray(new VariableBinding[responsePDU.size()])));
     }
   }
   callback.onResponse(response, url, event.getUserObject());
 }
Example #4
0
  public void SentGetSnmp() throws IOException {

    TransportMapping transport = new DefaultUdpTransportMapping();
    transport.listen();

    // Target
    CommunityTarget target = CreateAndSetTarget();

    // PDU
    PDU pdu = CreateAndSetPdu();

    // SNMP
    Snmp snmp = new Snmp(transport);

    // System.out.println("Sending request to " + ipFromInput + " ...");
    ResponseEvent response = snmp.get(pdu, target);

    if (response != null) {
      // System.out.println("Got response from " + ipFromInput);
      PDU responsePdu = response.getResponse();

      if (responsePdu != null) {
        int errorStatus = responsePdu.getErrorStatus();
        int errorIndex = responsePdu.getErrorIndex();
        String errorStatusText = responsePdu.getErrorStatusText();

        if (errorStatus == PDU.noError) {
          readResponse(responsePdu.getVariableBindings());
          // System.out.println(responsePdu.getVariableBindings().getClass());
          // System.out.println("SNMP get response: " + responsePdu.getVariableBindings());
        } else {
          System.out.println("Error: Request Failed");
          System.out.println("Error Status: " + errorStatus);
          System.out.println("Error Index: " + errorIndex);
          System.out.println("Error Status Text: " + errorStatusText);
        }
      } else {
        System.out.println("Error: PDU response is null");
      }
    } else {
      System.out.println("Error: Agent Timeout");
    }
    snmp.close();
  }
Example #5
0
  /**
   * The method get can be specified with an Array of requested OIDs. A Vector with elements of the
   * subclass VariableBinding will be returned. OID requested from the method GET can only return a
   * value. Therefore the OIDd must be a scalar and not a branch.
   *
   * @param oids - the requested OIDs
   * @return - a Vector with VariableBindings
   * @throws SNMPTimeOutException - will be thrown if a timeout with request happens
   * @throws PDURequestFailedException - will be thrown if an error occurs within the request
   * @see org.snmp4j.smi.VariableBinding
   */
  public Vector<? extends VariableBinding> get(OID[] oids)
      throws SNMPTimeOutException, PDURequestFailedException {
    ResponseEvent responseEvent = null;
    Vector<? extends VariableBinding> vbs = null;
    try {
      // send the PDU
      responseEvent = snmp.send(createPDU(PDU.GET, oids), authentication.getTarget());
      Logger.getLogger(SnmpManager.class.getName()).log(Level.INFO, responseEvent.toString());
    } catch (IOException e) {
      System.err.println(e.getMessage());
    }
    // extract the response PDU (could be null if timed out)
    if (responseEvent != null) {
      PDU responsePDU = responseEvent.getResponse();
      if (checkResponsePDU(responsePDU)) vbs = responsePDU.getVariableBindings();
    } else {
      throw new SNMPTimeOutException();
    }

    return vbs;
  }
Example #6
0
  public static List<String> get(
      Snmp snmp, String address, String community, int version, int retry, String[] oids) {

    List<String> list = new ArrayList<String>();

    Address targetAddress = GenericAddress.parse(address);
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString(community));
    target.setAddress(targetAddress);
    target.setVersion(version);
    target.setTimeout(1000);
    target.setRetries(retry);

    PDU pdu = new PDU();
    pdu.setType(PDU.GET);
    for (String oid : oids) {
      pdu.add(new VariableBinding(new OID(oid)));
    }

    try {
      ResponseEvent response = snmp.send(pdu, target);
      PDU resposePdu = response.getResponse();
      if (resposePdu != null) {
        Vector<?> v = resposePdu.getVariableBindings();
        for (Object o : v) {
          if (o instanceof VariableBinding) {
            VariableBinding vb = (VariableBinding) o;
            String r = vb.getVariable().toString();
            list.add(r);
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    return list;
  }
Example #7
0
  /**
   * Read a variable saved into @DriverConfiguration object
   *
   * @param propertyConfiguration driver configuration object
   * @throws GenericException if configuration fatal error
   */
  @Override
  public void readValue(DriverConfiguration propertyConfiguration) throws GenericException {
    try {
      ResponseEvent response = snmpGet(String.valueOf(propertyConfiguration.getValue()));
      if (response != null) {
        if (log.isDebugEnabled()) {
          log.debug("Got Snmp Get Response from Agent");
        }
        PDU responsePDU = response.getResponse();

        if (responsePDU != null) {
          int errorStatus = responsePDU.getErrorStatus();

          if (errorStatus == PDU.noError) {
            Vector<? extends VariableBinding> variableBindings = responsePDU.getVariableBindings();
            if (log.isDebugEnabled()) {
              log.debug(String.format("Snmp Get Response = %s", variableBindings));
            }
            VariableBinding variableBinding = variableBindings.get(0);
            Variable variable = variableBinding.getVariable();
            Object value = convert(variable, getValueType(variable));
            setValue(propertyConfiguration, value);
          } else {
            notifyResponse(response, propertyConfiguration.getName());
          }
        } else {
          if (log.isDebugEnabled()) {
            log.debug("Error: Response PDU is null");
          }
        }
      } else {
        notifyResponse(response, propertyConfiguration.getName());
      }
    } catch (Exception e) {
      throw new GenericException(e);
    }
  }
Example #8
0
 private static Vector<VariableBinding> getTableRow(
     Snmp snmp, CommunityTarget target, String[] colOids, String firstOid) {
   PDU pdu = new PDU();
   pdu.setType(PDU.GETNEXT);
   for (String oid : colOids) {
     pdu.add(new VariableBinding(new OID(oid)));
   }
   Vector<VariableBinding> v = null;
   try {
     ResponseEvent response = snmp.send(pdu, target);
     PDU resposePdu = response.getResponse();
     if (resposePdu != null) {
       v = resposePdu.getVariableBindings();
       if (v != null && v.size() > 0) {
         VariableBinding vb = v.get(0);
         String oid = vb.getOid().toString();
         if (!oid.startsWith(firstOid)) return null;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return v;
 }
  /** {@inheritDoc} */
  public PDU processPdu(PDU pdu) throws SnmpToolkitException {
    Log log = LogFactory.getLog(this.getClass());

    // 応答用のPDUを生成する
    PDU retPdu = new PDU();
    retPdu.setType(PDU.RESPONSE);

    // 要求のリクエストIDを取得し、応答PDUにセットする
    Integer32 requestID = pdu.getRequestID();
    retPdu.setRequestID(requestID);

    // SNMP4J用の型変換オブジェクト
    SnmpVariableHelper varHelper = new Snmp4jVariableHelper();

    // AgentServiceからAgentを取得する
    Agent agent = this.agentService_.getAgent();

    // 要求PDUのVarbindを走査する
    int varCount = 0;
    List<?> reqVarbinds = pdu.getVariableBindings();
    for (Object reqVarbindObj : reqVarbinds) {
      varCount++;

      // 要求されているOIDを取得する
      VariableBinding reqVarbind = (VariableBinding) reqVarbindObj;
      OID oid = reqVarbind.getOid();

      // GETNEXTでない場合は、指定されたOIDそのものを取得しようとする
      // GETNEXTの場合は、指定されたOID配下で最も近いオブジェクトを探す
      boolean exact = (pdu.getType() != PDU.GETNEXT);
      SnmpVarbind foundVarbind = agent.findObject(oid.toString(), exact);
      if (foundVarbind == null) {
        // Varbindが見つからなかった場合はnoSuchNameを返す
        log.warn("varbind is not found. oid=" + oid.toString());

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_SUCH_NAME);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      // READ-WRITEでなければエラー応答を返す
      String accessibility = foundVarbind.getAccessibility();
      if (accessibility.equals(SnmpVarbind.ACCESSIBILITY_NOT_ACCESSIBLE) == true) {
        log.warn("varbind is not accessible. accessibility=" + accessibility);

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_ACCESS);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      try {
        // 正常の応答を返す
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_SUCCESS);
        retPdu.setErrorIndex(0);

        log.debug("varbind is found: " + foundVarbind.toString());
        String typeStr = foundVarbind.getType();
        Object retValueObj = foundVarbind.getValue();
        Variable retObject = (Variable) varHelper.createAsnObject(retValueObj, typeStr);

        OID retOID = new OID(foundVarbind.getOid());
        VariableBinding retVarbind = new VariableBinding(retOID, retObject);
        retPdu.add(retVarbind);
      } catch (Exception exception) {
        log.warn("exception occured", exception);

        // 未知のエラーを示す応答PDUを作成する
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_GENERAL_ERROR);
        retPdu.setErrorIndex(varCount);

        if (foundVarbind != null) {
          OID retOID = new OID(foundVarbind.getOid());
          Variable retObject = new Null();
          VariableBinding retVarbind = new VariableBinding(retOID, retObject);
          retPdu.add(retVarbind);
        }
      }
    }
    return retPdu;
  }
    /**
     * This method will be called whenever a pdu is received on the given port specified in the
     * listen() method.
     */
    public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
      logger.info("Received PDU...");
      PDU pdu = cmdRespEvent.getPDU();

      if (pdu != null) {
        try {
          Event event;
          Map<String, String> headers;
          StringBuilder stringBuilder = new StringBuilder();

          // getVariableBindings: Gets the variable binding vector.
          Vector<? extends VariableBinding> vbs = pdu.getVariableBindings();
          for (VariableBinding vb : vbs) {
            // To extract only the value of the OID
            // stringBuilder.append(vb.getVariable().toString());
            stringBuilder.append(vb.toString() + ",");
          }

          String messageString = stringBuilder.toString();

          // trick: remove the last comma
          messageString = messageString.replaceAll(",$", "");

          byte[] message = messageString.getBytes();

          event = new SimpleEvent();
          headers = new HashMap<String, String>();

          headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
          logger.info("Message: {}", messageString);
          event.setBody(message);
          event.setHeaders(headers);

          if (event == null) {
            return;
          }

          // store the event to underlying channels(s)
          getChannelProcessor().processEvent(event);

          counterGroup.incrementAndGet("events.success");

        } catch (ChannelException ex) {
          counterGroup.incrementAndGet("events.dropped");
          logger.error("Error writting to channel", ex);
          return;
        }

        logger.info("Trap Type = " + pdu.getType());
        logger.info("Variable Bindings = " + pdu.getVariableBindings());

        int pduType = pdu.getType();

        if ((pduType != PDU.TRAP)
            && (pduType != PDU.V1TRAP)
            && (pduType != PDU.REPORT)
            && (pduType != PDU.RESPONSE)) {
          pdu.setErrorIndex(0);
          pdu.setErrorStatus(0);
          pdu.setType(PDU.RESPONSE);
          StatusInformation statusInformation = new StatusInformation();
          StateReference ref = cmdRespEvent.getStateReference();

          try {
            System.out.println(cmdRespEvent.getPDU());
            cmdRespEvent
                .getMessageDispatcher()
                .returnResponsePdu(
                    cmdRespEvent.getMessageProcessingModel(),
                    cmdRespEvent.getSecurityModel(),
                    cmdRespEvent.getSecurityName(),
                    cmdRespEvent.getSecurityLevel(),
                    pdu,
                    cmdRespEvent.getMaxSizeResponsePDU(),
                    ref,
                    statusInformation);
          } catch (MessageException ex) {
            System.err.println("Error while sending response: " + ex.getMessage());
            LogFactory.getLogger(SnmpRequest.class).error(ex);
          }
        }
      }
    }