Example #1
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;
 }
Example #2
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());
       }
     }
   }
 }
  /**
   * 向管理进程发送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());
      }
    }
  }
Example #4
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;
   }
 }
Example #5
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;
   }
 }
Example #6
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);
 }
Example #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;
 }
Example #8
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;
 }
  /**
   * @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;
        }
      }
    }
  }
 /**
  * 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();
 }
Example #11
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;
 }
Example #12
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;
  }
Example #13
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();
    }
  }
  /** {@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;
  }
Example #15
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);
  }