/**
   * 向管理进程发送Trap报文
   *
   * @throws IOException
   */
  public void sendPDU() throws IOException {

    // 设置 target
    CommunityTarget target = new CommunityTarget();
    target.setAddress(targetAddress);

    // 通信不成功时的重试次数
    target.setRetries(2);
    // 超时时间
    target.setTimeout(1500);
    // snmp版本
    target.setVersion(SnmpConstants.version2c);

    // 创建 PDU
    PDU pdu = new PDU();
    pdu.add(
        new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"), new OctetString("SnmpTrap")));
    pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.2"), new OctetString("JavaEE")));
    pdu.add(
        new VariableBinding(
            new OID(".1.3.6.1.4.1.12612.220.11.1.3.0.1"), new OctetString("test_barco")));
    pdu.setType(PDU.TRAP);

    // 向Agent发送PDU,并接收Response
    ResponseEvent respEvnt = snmp.send(pdu, target);

    // 解析Response
    if (respEvnt != null && respEvnt.getResponse() != null) {
      Vector<VariableBinding> recVBs = respEvnt.getResponse().getVariableBindings();
      for (int i = 0; i < recVBs.size(); i++) {
        VariableBinding recVB = recVBs.elementAt(i);
        System.out.println(recVB.getOid() + " : " + recVB.getVariable());
      }
    }
  }
Пример #2
0
  VariableBinding getVarBindForSetRequest(String oid, int type, String value) {
    VariableBinding vb = new VariableBinding(new OID(oid));

    if (value != null) {
      Variable variable;
      switch (type) {
        case DSnmpMibRecord.VALUE_TYPE_INTEGER32:
          variable = new Integer32(Integer.parseInt(value));
          break;
        case DSnmpMibRecord.VALUE_TYPE_UNSIGNED_INTEGER32:
          variable = new UnsignedInteger32(Long.parseLong(value));
          break;
        case DSnmpMibRecord.VALUE_TYPE_OCTET_STRING:
          variable = new OctetString(value);
          break;
        case DSnmpMibRecord.VALUE_TYPE_NULL:
          variable = new Null();
          break;
        case DSnmpMibRecord.VALUE_TYPE_OID:
          variable = new OID(value);
          break;
        case DSnmpMibRecord.VALUE_TYPE_TIMETICKS:
          variable = new TimeTicks(Long.parseLong(value));
          break;
        case DSnmpMibRecord.VALUE_TYPE_IP_ADDRESS:
          variable = new IpAddress(value);
          break;
        default:
          throw new IllegalArgumentException("Variable type " + type + " not supported");
      }
      vb.setVariable(variable);
    }
    return vb;
  }
Пример #3
0
  /**
   * Encodes a <code>Variable</code> to an <code>OutputStream</code>.
   *
   * @param outputStream an <code>OutputStream</code>.
   * @throws IOException if an error occurs while writing to the stream.
   */
  @Override
  public void encodeBER(OutputStream outputStream) throws IOException {
    BER.encodeHeader(outputStream, type, getBERPayloadLength());

    if (type == PDU.V1TRAP) {
      enterprise.encodeBER(outputStream);
      agentAddress.encodeBER(outputStream);
      genericTrap.encodeBER(outputStream);
      specificTrap.encodeBER(outputStream);
      timestamp.encodeBER(outputStream);
    } else {
      requestID.encodeBER(outputStream);
      errorStatus.encodeBER(outputStream);
      errorIndex.encodeBER(outputStream);
    }
    int vbLength = 0;
    for (VariableBinding variableBinding : variableBindings) {
      vbLength += variableBinding.getBERLength();
    }
    BER.encodeHeader(outputStream, BER.SEQUENCE, vbLength);
    for (VariableBinding vb : variableBindings) {
      if (!isVariableV1(vb.getVariable())) {
        throw new IOException("Cannot encode Counter64 into a SNMPv1 PDU");
      }
      vb.encodeBER(outputStream);
    }
  }
Пример #4
0
 public void verify(VariableBinding vb) {
   assertNotNull("variable binding should not be null", vb);
   Variable val = vb.getVariable();
   assertNotNull("variable should not be null", val);
   assertEquals("OID (value: " + val + ")", new OID(m_expectedOid), vb.getOid());
   assertEquals("syntax", m_expectedSyntax, vb.getSyntax());
   assertEquals("value", m_expectedValue, val);
 }
Пример #5
0
 /**
  * The method getAsString(Oid oid) is using the @see SnmpManager#get to get a String value of the
  * specified OID.
  *
  * @param oid - the requested OID
  * @return - a String with the result from the specified OID
  * @throws SNMPTimeOutException - will be thrown if a timeout with request happens
  * @throws snmp.exceptions.OIDDoesNotExistsException - will be thrown if the specified OID does
  *     not exist
  * @throws PDURequestFailedException - will be thrown if an error occurs within the request
  */
 public String getAsString(OID oid)
     throws SNMPTimeOutException, PDURequestFailedException, OIDDoesNotExistsException {
   // extract the response PDU (could be null if timed out)
   VariableBinding ret = get(new OID[] {oid}).get(0);
   String response = ret.getVariable().toString();
   if (response.equals("noSuchObject")) throw new OIDDoesNotExistsException();
   return response;
 }
Пример #6
0
  /**
   * Decodes a <code>Variable</code> from an <code>InputStream</code>.
   *
   * @param inputStream an <code>InputStream</code> containing a BER encoded byte stream.
   * @throws IOException
   */
  @Override
  public void decodeBER(BERInputStream inputStream) throws IOException {
    MutableByte pduType = new MutableByte();
    int length = BER.decodeHeader(inputStream, pduType);
    int pduStartPos = (int) inputStream.getPosition();

    switch (pduType.getValue()) {
      case PDU.SET:
      case PDU.GET:
      case PDU.GETNEXT:
      case PDU.V1TRAP:
      case PDU.RESPONSE:
        break;
        // The following PDU types are not supported by the SNMPv1 standard!
      case PDU.NOTIFICATION:
      case PDU.INFORM:
        if (SNMP4JSettings.isAllowSNMPv2InV1()) {
          break;
        }
        // fall through
      default:
        throw new IOException("Unsupported PDU type: " + pduType.getValue());
    }
    this.setType(pduType.getValue());
    if (getType() == PDU.V1TRAP) {
      enterprise.decodeBER(inputStream);
      agentAddress.decodeBER(inputStream);
      genericTrap.decodeBER(inputStream);
      specificTrap.decodeBER(inputStream);
      timestamp.decodeBER(inputStream);
    } else {
      requestID.decodeBER(inputStream);
      errorStatus.decodeBER(inputStream);
      errorIndex.decodeBER(inputStream);
    }
    // reusing pduType here to save memory ;-)
    pduType = new BER.MutableByte();
    int vbLength = BER.decodeHeader(inputStream, pduType);
    if (pduType.getValue() != BER.SEQUENCE) {
      throw new IOException("Encountered invalid tag, SEQUENCE expected: " + pduType.getValue());
    }
    // rest read count
    int startPos = (int) inputStream.getPosition();
    variableBindings = new Vector<>();
    while (inputStream.getPosition() - startPos < vbLength) {
      VariableBinding vb = new VariableBinding();
      vb.decodeBER(inputStream);
      if (!isVariableV1(vb.getVariable())) {
        throw new MessageException("Counter64 encountered in SNMPv1 PDU " + "(RFC 2576 §4.1.2.1)");
      }
      variableBindings.add(vb);
    }
    if (BER.isCheckSequenceLength()) {
      BER.checkSequenceLength(vbLength, (int) inputStream.getPosition() - startPos, this);
      BER.checkSequenceLength(length, (int) inputStream.getPosition() - pduStartPos, this);
    }
  }
Пример #7
0
 private SnmpOidValuePair outputResponse(VariableBinding vb) {
   SnmpOidValuePair oidval = new SnmpOidValuePair();
   oidval.oid = vb.getOid().toString();
   oidval.value_str = vb.getVariable().toString();
   if (m_snmpResponseHandler != null) {
     m_snmpResponseHandler.responseReceived(oidval);
   }
   return oidval;
 }
Пример #8
0
 public void set(VariableBinding binding) {
   switch (binding.getOid().get(9)) {
     case 1:
       setUdpEndpointLocalAddressType(binding.getVariable().toInt());
       break;
     case 2:
       setUdpEndpointLocalAddress(binding.getVariable().toString());
       break;
     case 3:
       setUdpEndpointLocalPort(binding.getVariable().toInt());
       break;
     case 4:
       setUdpEndpointRemoteAddressType(binding.getVariable().toInt());
       break;
     case 5:
       setUdpEndpointRemoteAddress(binding.getVariable().toString());
       break;
     case 6:
       setUdpEndpointRemotePort(binding.getVariable().toInt());
       break;
     case 7:
       setUdpEndpointInstance(binding.getVariable().toInt());
       break;
     case 8:
       setUdpEndpointProcess(binding.getVariable().toInt());
       break;
   }
 }
Пример #9
0
 public void set(VariableBinding binding) {
   switch (binding.getOid().get(10)) {
     case 1:
       setEventIndex(binding.getVariable().toInt());
       break;
     case 2:
       setEventDescription(binding.getVariable().toString());
       break;
     case 3:
       setEventType(binding.getVariable().toInt());
       break;
     case 4:
       setEventCommunity(binding.getVariable().toString());
       break;
     case 5:
       setEventLastTimeSent(binding.getVariable().toInt());
       break;
     case 6:
       setEventOwner(binding.getVariable().toString());
       break;
     case 7:
       setEventStatus(binding.getVariable().toInt());
       break;
   }
 }
Пример #10
0
 /**
  * Add directly a VariableBinding to the map it will be stored as a key/value and the original
  * snmp datas will be lost only not
  *
  * @param vb
  */
 public boolean addVariable(VariableBinding vb) {
   boolean retValue = false;
   if (vb == null) {
     logger.error("null variable to add ?");
   } else if (!vb.isException()) {
     OID vbOid = vb.getOid();
     put(vbOid, convertVar(vb.getVariable()));
     retValue = true;
   } else {
     errors.put(vb.getOid(), vb.getSyntax());
     int exception = vb.getSyntax();
     String exceptionName = "";
     switch (exception) {
       case SMIConstants.EXCEPTION_END_OF_MIB_VIEW:
         exceptionName = "End of mib view";
         break;
       case SMIConstants.EXCEPTION_NO_SUCH_INSTANCE:
         exceptionName = "No such instance";
         break;
       case SMIConstants.EXCEPTION_NO_SUCH_OBJECT:
         exceptionName = "No such object";
         break;
       default:
         exceptionName = "Unknown exception";
         break;
     }
     logger.trace("Exception " + exceptionName + " for " + vb.getOid());
   }
   return retValue;
 }
  /**
   * @param ip
   * @param community
   */
  public static void snmpGetList(String ip, String community, List<String> oidList) {
    CommunityTarget target = SnmpUtil.createDefault(ip, community);

    Snmp snmp = null;
    try {
      PDU pdu = new PDU();

      for (String oid : oidList) {
        pdu.add(new VariableBinding(new OID(oid)));
      }

      DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
      transport.listen();
      snmp = new Snmp(transport);

      System.out.println("------->发送消息<-------");
      pdu.setType(PDU.GET);
      ResponseEvent respEvent = snmp.send(pdu, target);
      System.out.println("PeerAddress:" + respEvent.getPeerAddress());
      PDU response = respEvent.getResponse();

      if (response == null) {
        System.out.println("response is null, request time out");
      } else {
        System.out.println("response pdu size is " + response.size());
        for (int i = 0; i < response.size(); i++) {
          VariableBinding vb = response.get(i);
          System.out.println(vb.getOid() + " = " + vb.getVariable());
        }
      }
      System.out.println("SNMP GET List OID value finished !");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("SNMP GetList Exception:" + e);
    } finally {
      if (snmp != null) {
        try {
          snmp.close();
        } catch (IOException ex1) {
          snmp = null;
        }
      }
    }
  }
Пример #12
0
 @Override
 protected int getBERPayloadLengthPDU() {
   if (getType() != PDU.V1TRAP) {
     return super.getBERPayloadLengthPDU();
   } else {
     int length = 0;
     // length for all vbs
     for (VariableBinding variableBinding : variableBindings) {
       length += variableBinding.getBERLength();
     }
     length += BER.getBERLengthOfLength(length) + 1;
     length += agentAddress.getBERLength();
     length += enterprise.getBERLength();
     length += genericTrap.getBERLength();
     length += specificTrap.getBERLength();
     length += timestamp.getBERLength();
     return length;
   }
 }
 /**
  * Method which takes a single OID and returns the response from the agent as a String.
  *
  * @param oid
  * @return
  * @throws IOException
  */
 public String getAsString(OID... oid) throws IOException {
   //        ResponseEvent event = get(new OID[]{oid});
   //        return event.getResponse().get(0).getVariable().toString();
   ResponseEvent event = get(oid);
   PDU response = event.getResponse();
   int size = oid.length;
   //        VariableBinding variableBinding=response.get(0);
   //        Variable variable=variableBinding.getVariable();
   //        String varStirng=variable.toString();
   //        return varStirng;
   StringBuilder builder = new StringBuilder();
   for (int i = 0; i < size; i++) {
     VariableBinding variableBinding = response.get(i);
     Variable variable = variableBinding.getVariable();
     String varStirng = variable.toString();
     String oi = variableBinding.getOid().toString();
     builder.append("oid: ").append(oi).append(" var: ").append(varStirng).append("\n");
   }
   return builder.toString();
 }
Пример #14
0
 private boolean processWalk(PDU response, PDU request, OID rootOID) throws SnmpException {
   if ((response == null)
       || (response.getErrorStatus() != 0)
       || (response.getType() == PDU.REPORT)) {
     return true;
   }
   boolean finished = false;
   OID lastOID = request.get(0).getOid();
   for (int i = 0; (!finished) && (i < response.size()); i++) {
     VariableBinding vb = response.get(i);
     if ((vb.getOid() == null)
         || (vb.getOid().size() < rootOID.size())
         || (rootOID.leftMostCompare(rootOID.size(), vb.getOid()) != 0)) {
       finished = true;
     } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
       outputResponse(vb);
       finished = true;
     } else if (vb.getOid().compareTo(lastOID) <= 0) {
       throw new SnmpException(
           "Variable received is not lexicographic successor of requested one:"
               + vb.toString()
               + " <= "
               + lastOID);
     } else {
       outputResponse(vb);
       lastOID = vb.getOid();
     }
   }
   if (response.size() == 0) {
     finished = true;
   }
   if (!finished) {
     VariableBinding next = response.get(response.size() - 1);
     next.setVariable(new Null());
     request.set(0, next);
     request.setRequestID(new Integer32(0));
   }
   return finished;
 }
Пример #15
0
 public void browse(URI url, SnmpUriCallback callback, Object userObject)
     throws UnknownHostException {
   Request request = createSnmpRequest(url);
   PDU pdu = request.getPdu();
   switch (request.getType()) {
     case GET:
       pdu.setType(PDU.GET);
       pdu.addAll(VariableBinding.createFromOIDs(request.getOIDs()));
       sendSnmpRequest(request, pdu, url, callback, userObject);
       break;
     case NEXT:
       pdu.setType(PDU.GETNEXT);
       pdu.addAll(VariableBinding.createFromOIDs(request.getOIDs()));
       sendSnmpRequest(request, pdu, url, callback, userObject);
       break;
     case SUBTREE:
       TreeUtils treeUtils = new TreeUtils(snmp, pduFactory);
       TreeListener treeListener = new AsyncTreeListener(url, callback);
       treeUtils.walk(request.getTarget(), request.getOIDs(), userObject, treeListener);
       break;
   }
 }
Пример #16
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;
  }
Пример #17
0
 /**
  * Creates a static managed object group for the sub-tree with the specified root OID.
  *
  * @param root the root OID of the sub-tree to be registered by this managed object.
  * @param vbs the variable bindings to be returned in this sub-tree.
  */
 public StaticMOGroup(OID root, VariableBinding[] vbs) {
   this.root = root;
   this.scope = new DefaultMOScope(root, true, root.nextPeer(), false);
   for (VariableBinding vb : vbs) {
     if ((vb.getOid() != null) && (vb.getVariable() != null)) {
       if ((vb.getOid().size() >= root.size())
           && (vb.getOid().leftMostCompare(root.size(), root) == 0)) {
         this.vbs.put(vb.getOid(), vb.getVariable());
       }
     }
   }
 }
Пример #18
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);
    }
  }
Пример #19
0
  public static List<String[]> getTable(
      Snmp snmp, String address, String community, int version, int retry, String[] colOids) {
    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.GETNEXT);
    for (String oid : colOids) {
      pdu.add(new VariableBinding(new OID(oid)));
    }
    int i = 0;
    String firstOid = colOids[0];
    Vector<VariableBinding> row = null;
    do {
      row = getTableRow(snmp, target, colOids, firstOid);
      if (row != null && colOids.length == row.size()) {
        String[] ss = new String[colOids.length];
        for (int n = 0; n < colOids.length; n++) {
          VariableBinding vb = row.get(n);
          String r = vb.getVariable().toString();
          colOids[n] = vb.getOid().toString();
          ss[n] = r;
        }
        list.add(ss);
      }
    } while (i++ < 200 && row != null);

    return list;
  }
Пример #20
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;
 }
Пример #21
0
  public void processPdu(CommandResponderEvent pRequest) {

    final PDU requestPdu = pRequest.getPDU();

    if (requestPdu == null) {
      return;
    }

    try {

      final PDU responsePdu = new PDU(requestPdu);
      responsePdu.setType(PDU.RESPONSE);

      if (requestPdu.getType() == PDU.GET) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String path = jmxMib.getPathFromOid(oid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else if (requestPdu.getType() == PDU.GETNEXT) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String next = jmxMib.getNextOidFromOid(oid.toString());

          if (next == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final OID nextOid = new OID(next);

          binding.setOid(nextOid);

          final String path = jmxMib.getPathFromOid(nextOid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else {

      }

      pRequest.getStateReference().setTransportMapping(pRequest.getTransportMapping());
      pRequest
          .getMessageDispatcher()
          .returnResponsePdu(
              pRequest.getMessageProcessingModel(),
              pRequest.getSecurityModel(),
              pRequest.getSecurityName(),
              pRequest.getSecurityLevel(),
              responsePdu,
              pRequest.getMaxSizeResponsePDU(),
              pRequest.getStateReference(),
              new StatusInformation());

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
    /**
     * 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);
          }
        }
      }
    }
Пример #23
0
  private void parseVariableBinding(Element variable, PDU pdu) throws Exception {
    String name = variable.attributeValue("name");
    String value = variable.attributeValue("value");
    String type = variable.attributeValue("type");
    String mibName = null;

    if (name == null) {
      throw new Exception("ERROR : The variablebinding name is required to send the variable.");
    }

    VariableBinding varBind = null;
    boolean found = false;
    if (name.startsWith(
        "1.")) // if name begin with digit 1 follow by a dot, it is an oid, else we consider it's a
    // variable mib
    {
      varBind = new VariableBinding(new OID(name));
      found = true;
    } else {
      if (name.contains(".")) {
        mibName = name.substring(0, name.indexOf('.'));
        name = name.substring(name.indexOf('.') + 1);
      }

      Mib[] mibs = mibLoader.getAllMibs();
      for (int i = 0; (i < mibs.length) && !found; i++) {
        Collection symbols = mibs[i].getAllSymbols();
        for (Object symb : symbols) {
          if (symb instanceof MibValueSymbol) {
            if (((MibValueSymbol) symb).getName().equalsIgnoreCase(name)) {
              if ((mibName == null)
                  || ((MibValueSymbol) symb).getMib().getName().equalsIgnoreCase(mibName)) {
                varBind =
                    new VariableBinding(new OID(((MibValueSymbol) symb).getValue().toString()));

                if (type == null) {
                  type = findType((MibValueSymbol) symb);
                }
                found = true;
                break;
              }
            }
          } else if (symb instanceof MibTypeSymbol) {
            //                        System.out.println("mibTypeSymbol " +
            // ((MibTypeSymbol)symb).getName() + " for mib name " + mibs[i].getName());
          } else if (symb instanceof MibMacroSymbol) {
            //                        System.out.println("mibMacroSymbol " +
            // ((MibMacroSymbol)symb).getName() + " for mib name " + mibs[i].getName());
          } else {
            throw new Exception(
                "ERROR : Unknown class for variablebinding \"" + symb.getClass() + "\"");
          }
        }
      }
    }
    if (!found) {
      throw new Exception(
          "ERROR : Unknown varbinding name \"" + name + "\" not found in the MIB files.");
    }

    if (type == null) // /if type not set, search in mib
    {
      Mib[] mibs = mibLoader.getAllMibs();
      for (int i = 0; (i < mibs.length); i++) {
        MibValueSymbol symbol = mibs[i].getSymbolByValue(varBind.getOid().toString());

        if (symbol != null) {
          // set type in function of information in variable
          type = findType(symbol);
          break;
        }
      }
    }

    if ((value != null) && (value.length() > 0)) {
      if (type == null) {
        throw new Exception(
            "ERROR : The variablebinding type is required : it is not defined nor in XML script nor in MIB files.");
      }
      if (type.equalsIgnoreCase("counter64")) {
        varBind.setVariable(new Counter64(Long.parseLong(value)));
      } else if (type.equalsIgnoreCase("integer32")) {
        varBind.setVariable(new Integer32(Integer.parseInt(value)));
      } else if (type.equalsIgnoreCase("octetString") || type.equalsIgnoreCase("octet string")) {
        varBind.setVariable(new OctetString(value));
      } else if (type.equalsIgnoreCase("opaque")) {
        varBind.setVariable(new Opaque(value.getBytes()));
      } else if (type.equalsIgnoreCase("oid")) {
        varBind.setVariable(new OID(value));
      } else if (type.equalsIgnoreCase("genericAddress")) {
        GenericAddress add = new GenericAddress();
        add.setValue(value);
        varBind.setVariable(add);
      } else if (type.equalsIgnoreCase("ipAddress")) {
        varBind.setVariable(new IpAddress(value));
      } else if (type.equalsIgnoreCase("unsignedInteger32")) {
        varBind.setVariable(new UnsignedInteger32(Integer.parseInt(value)));
      } else if (type.equalsIgnoreCase("counter32")) {
        varBind.setVariable(new Counter32(Long.parseLong(value)));
      } else if (type.equalsIgnoreCase("gauge32")) {
        varBind.setVariable(new Gauge32(Long.parseLong(value)));
      } else if (type.equalsIgnoreCase("timeTicks")) {
        varBind.setVariable(new TimeTicks(Long.parseLong(value)));
      } else {
        throw new Exception(
            "Error : Unknown variablebinding type \""
                + type
                + "\" : not understood by the application");
      }
    }

    pdu.add(varBind);
  }
Пример #24
0
  public Variable getVariable(String name) {
    OID oid;
    OctetString context = null;
    int pos = name.indexOf(':');
    if (pos >= 0) {
      context = new OctetString(name.substring(0, pos));
      oid = new OID(name.substring(pos + 1, name.length()));
    } else {
      oid = new OID(name);
    }
    final DefaultMOContextScope scope = new DefaultMOContextScope(context, oid, true, oid, true);
    MOQuery query = new DefaultMOQuery(scope, false, this);
    ManagedObject mo = server.lookup(query);
    if (mo != null) {
      final VariableBinding vb = new VariableBinding(oid);
      final RequestStatus status = new RequestStatus();
      SubRequest req =
          new SubRequest() {
            private boolean completed;
            private MOQuery query;

            public boolean hasError() {
              return false;
            }

            public void setErrorStatus(int errorStatus) {
              status.setErrorStatus(errorStatus);
            }

            public int getErrorStatus() {
              return status.getErrorStatus();
            }

            public RequestStatus getStatus() {
              return status;
            }

            public MOScope getScope() {
              return scope;
            }

            public VariableBinding getVariableBinding() {
              return vb;
            }

            public Request getRequest() {
              return null;
            }

            public Object getUndoValue() {
              return null;
            }

            public void setUndoValue(Object undoInformation) {}

            public void completed() {
              completed = true;
            }

            public boolean isComplete() {
              return completed;
            }

            public void setTargetMO(ManagedObject managedObject) {}

            public ManagedObject getTargetMO() {
              return null;
            }

            public int getIndex() {
              return 0;
            }

            public void setQuery(MOQuery query) {
              this.query = query;
            }

            public MOQuery getQuery() {
              return query;
            }

            public SubRequestIterator repetitions() {
              return null;
            }

            public void updateNextRepetition() {}

            public Object getUserObject() {
              return null;
            }

            public void setUserObject(Object userObject) {}
          };
      mo.get(req);
      return vb.getVariable();
    }
    return null;
  }
  /** {@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;
  }