コード例 #1
0
  /**
   * 向管理进程发送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
  public void testTrap() throws Exception {

    File alarmsFile = new File("alarms.txt");
    alarmsFile.delete();

    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    OID oid = new OID("1.2.3.4.5");
    trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid));
    trap.add(
        new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000))); // put your uptime here
    trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));

    Variable alarmCode = new OctetString("777");
    Variable agentId = new OctetString("AGENT_ID");
    Variable alarmText = new OctetString("ALARM");
    Variable agentAddress = new OctetString("127.0.0.1/161");
    trap.add(new VariableBinding(new OID("1.2.3.4.5.1"), alarmCode));
    trap.add(new VariableBinding(new OID("1.2.3.4.5.2"), agentId));
    trap.add(new VariableBinding(new OID("1.2.3.4.5.3"), alarmText));
    trap.add(new VariableBinding(new OID("1.2.3.4.5.4"), agentAddress));

    server.readAndSaveTrap(trap);

    assertTrue(alarmsFile.exists());

    String fileContent = SnmpNmsTest.readFileAsString("alarms.txt");
    assertTrue(fileContent.indexOf("AGENT_ID") > -1);
    assertTrue(fileContent.indexOf("777") > -1);
    assertTrue(fileContent.indexOf("ALARM") > -1);
  }
コード例 #3
0
ファイル: SnmpGetter.java プロジェクト: tommyNy/get-SNMP
 private PDU CreateAndSetPdu() {
   PDU pdu = new PDU();
   pdu.add(new VariableBinding(new OID(oidFromInput)));
   pdu.setType(PDU.GET);
   pdu.setRequestID(new Integer32(2));
   return pdu;
 }
コード例 #4
0
ファイル: SnmpLib.java プロジェクト: onebudwazer/my_repo
  public void snmpWalk(String oidFrom) throws SnmpException {
    PDU request = new PDU();
    request.setType(PDU.GETNEXT);
    request.add(new VariableBinding(new OID(oidFrom)));
    request.setNonRepeaters(0);
    OID rootOID = request.get(0).getOid();
    PDU response = null;

    int objects = 0;
    int requests = 0;
    long startTime = System.currentTimeMillis();

    try {
      Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
      snmp.listen();
      m_sessionDestroyed = false;
      do {
        requests++;
        ResponseEvent responseEvent = snmp.send(request, getTarget(getReadCommunity()));
        response = responseEvent.getResponse();
        if (response != null) {
          objects += response.size();
        }
      } while (!processWalk(response, request, rootOID) && !m_sessionDestroyed);

    } catch (SnmpException e) {
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw new SnmpException(e.getMessage());
    }
    if (m_snmpResponseHandler != null) {
      m_snmpResponseHandler.requestStats(requests, objects, System.currentTimeMillis() - startTime);
    }
  }
コード例 #5
0
 private ResponseEvent snmpGet(String targetOid) throws IOException {
   PDU pdu = new PDU();
   pdu.add(new VariableBinding(new OID(targetOid)));
   pdu.setType(PDU.GET);
   // send the PDU
   return snmp.send(pdu, target);
 }
コード例 #6
0
ファイル: LLDPMibIT.java プロジェクト: GuanglinDu/opennms
  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();
  }
コード例 #7
0
ファイル: SnmpV3.java プロジェクト: aaly-tgm/rtn
 /**
  * This method creates the requst and puts it in an PDU object. This object will be returnd and
  * used from Methods such as get,walk and getnext.
  *
  * @param type - the type of the response, possible are PDU.GET,PDU.GETNEXT, PDU.GETBULK
  * @param oids - the requested OIDs
  * @return - the request PDU
  * @see org.snmp4j.ScopedPDU
  */
 public PDU createPDU(int type, OID[] oids) {
   // create the PDU
   PDU requestPDU = new ScopedPDU();
   requestPDU.setType(type);
   // put the oid you want to get
   for (OID oid : oids) {
     requestPDU.add(new VariableBinding(oid));
   }
   return requestPDU;
 }
コード例 #8
0
 /**
  * This method is capable of handling multiple OIDs
  *
  * @param oids
  * @return
  * @throws IOException
  */
 public ResponseEvent get(OID... oids) throws IOException {
   PDU pdu = new PDU();
   for (OID oid : oids) {
     pdu.add(new VariableBinding(oid));
   }
   pdu.setType(PDU.GET);
   ResponseEvent event = snmp.send(pdu, getTarget(), null);
   if (event != null) {
     return event;
   }
   throw new RuntimeException("GET timed out");
 }
コード例 #9
0
ファイル: SnmpURI.java プロジェクト: hikumar/snmp4j
  public void updateByValue(
      URI url, List<Variable> values, SnmpUriCallback callback, Object userObject)
      throws UnknownHostException {
    Request request = createSnmpRequest(url);
    PDU pdu = request.getPdu();
    pdu.setType(PDU.SET);
    OID[] oids = request.getOIDs();
    for (int i = 0; i < oids.length && i < values.size(); i++) {
      pdu.add(new VariableBinding(oids[i], values.get(i)));
    }

    sendSnmpRequest(request, pdu, url, callback, userObject);
  }
コード例 #10
0
ファイル: SnmpURI.java プロジェクト: hikumar/snmp4j
 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;
   }
 }
コード例 #11
0
ファイル: SnmpURI.java プロジェクト: hikumar/snmp4j
  public void sendByBinding(
      URI url,
      List<VariableBinding> values,
      int pduType,
      SnmpUriCallback callback,
      Object userObject)
      throws UnknownHostException {
    Request request = createSnmpRequest(url);
    PDU pdu = request.getPdu();
    pdu.setType(pduType);
    for (VariableBinding vb : values) {
      pdu.add(vb);
    }

    sendSnmpRequest(request, pdu, url, callback, userObject);
  }
コード例 #12
0
  private PDU createPDU(SnmpTrapInfo snmpTrapInfo) {
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    int alertType = snmpTrapInfo.getAlertType() + 1;
    if (alertType > 0) {
      trap.add(
          new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
      trap.add(
          new VariableBinding(
              SnmpConstants.snmpTrapOID, getOID(CsSnmpConstants.TRAPS_PREFIX + alertType)));
      trap.add(
          new VariableBinding(
              getOID(CsSnmpConstants.DATA_CENTER_ID),
              new UnsignedInteger32(snmpTrapInfo.getDataCenterId())));
      trap.add(
          new VariableBinding(
              getOID(CsSnmpConstants.POD_ID), new UnsignedInteger32(snmpTrapInfo.getPodId())));
      trap.add(
          new VariableBinding(
              getOID(CsSnmpConstants.CLUSTER_ID),
              new UnsignedInteger32(snmpTrapInfo.getClusterId())));

      if (snmpTrapInfo.getMessage() != null) {
        trap.add(
            new VariableBinding(
                getOID(CsSnmpConstants.MESSAGE), new OctetString(snmpTrapInfo.getMessage())));
      } else {
        throw new CloudRuntimeException(" What is the use of alert without message ");
      }

      if (snmpTrapInfo.getGenerationTime() != null) {
        trap.add(
            new VariableBinding(
                getOID(CsSnmpConstants.GENERATION_TIME),
                new OctetString(snmpTrapInfo.getGenerationTime().toString())));
      } else {
        trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME)));
      }
    } else {
      throw new CloudRuntimeException(" Invalid alert Type ");
    }

    return trap;
  }
コード例 #13
0
 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;
 }
コード例 #14
0
  /**
   * @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;
        }
      }
    }
  }
コード例 #15
0
ファイル: SnmpLib.java プロジェクト: onebudwazer/my_repo
  void snmpSetValue(String oid, int syntax, String value) throws SnmpException {
    VariableBinding varbind = getVarBindForSetRequest(oid, syntax, value);

    PDU request = new PDU();
    request.setType(PDU.SET);
    request.add(varbind);
    PDU response = null;

    long startTime = System.currentTimeMillis();

    try {
      Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
      snmp.listen();
      ResponseEvent responseEvent = snmp.send(request, getTarget(getWriteCommunity()));
      response = responseEvent.getResponse();
      // System.out.println(response);
    } catch (Exception e) {
      e.printStackTrace();
      throw new SnmpException(e.getMessage());
    }
  }
コード例 #16
0
  /**
   * This method returns a Target, which contains information about where the data should be fetched
   * and how.
   *
   * @return
   * @throws IOException
   */
  private Target getTarget() throws IOException {
    Address targetAddress = GenericAddress.parse(address);
    //		System.out.println(targetAddress.isValid());
    //		CommunityTarget target = new CommunityTarget();
    //		target.setCommunity(new OctetString("public"));
    //		target.setAddress(targetAddress);
    //		System.out.println(target.getAddress());
    //		target.setRetries(2);
    //		target.setTimeout(5500);
    //		target.setVersion(SnmpConstants.version2c);
    //		System.out.println(target.toString());
    //		return target;

    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString(COMMUNITYKEY));
    target.setAddress(targetAddress);
    target.setRetries(2);
    target.setTimeout(100);
    target.setVersion(SnmpConstants.version1);
    // creating PDU
    PDU pdu = new PDU();
    pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 1})));
    pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 2})));
    pdu.setType(PDU.GETNEXT);
    // sending request
    ResponseListener listener =
        new ResponseListener() {
          public void onResponse(ResponseEvent event) {
            // Always cancel async request when response has been received
            // otherwise a memory leak is created! Not canceling a request
            // immediately can be useful when sending a request to a broadcast
            // address.
            ((Snmp) event.getSource()).cancel(event.getRequest(), this);
            // System.out.println("Received response PDU is: "+event.getResponse());
          }
        };
    snmp.send(pdu, target, null, listener);
    return target;
  }
コード例 #17
0
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    TransportMapping transport = new DefaultUdpTransportMapping();
    Snmp snmp = new Snmp(transport);

    MessageDispatcherImpl dispatcher = new MessageDispatcherImpl();

    transport.listen();
    Address targetAddress = new UdpAddress("202.144.0.178/161");
    // setting up target
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setAddress(targetAddress);
    target.setRetries(2);
    target.setTimeout(1500);
    target.setVersion(SnmpConstants.version1);
    // creating PDU
    PDU pdu = new PDU();
    pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 1})));
    pdu.add(new VariableBinding(new OID(new int[] {1, 3, 6, 1, 2, 1, 1, 2})));
    pdu.setType(PDU.GETNEXT);
    // sending request
    ResponseListener listener =
        new ResponseListener() {
          public void onResponse(ResponseEvent event) {
            // Always cancel async request when response has been received
            // otherwise a memory leak is created! Not canceling a request
            // immediately can be useful when sending a request to a
            // broadcast
            // address.
            ((Snmp) event.getSource()).cancel(event.getRequest(), this);
            System.out.println("Received response PDU is: " + event.getResponse());
          }
        };
    snmp.set(pdu, target, null, listener);

    //		snmp.sendPDU(pdu, target, null, listener);

  }
コード例 #18
0
ファイル: SnmpUtil.java プロジェクト: zhangzuoqiang/wnm
  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;
  }
コード例 #19
0
 public void snmpSet(String strAddress, String community, String strOID, int Value) {
   strAddress = strAddress + "/" + 161; // Direccion + Puerto SNMP
   Address targetAddress = GenericAddress.parse(strAddress); // direccion con puerto
   Snmp snmp;
   try {
     TransportMapping transport = new DefaultUdpTransportMapping();
     snmp = new Snmp(transport);
     transport.listen();
     /*
      * Este metodo regresa un Target, que contiene informacion acerca de los
      * datos y como deben ser mostrados y sus rangos.
      */
     CommunityTarget target =
         new CommunityTarget(); // representa las propiedades del target SNMP basado en proceso de
     // modelos
     target.setCommunity(new OctetString(community));
     target.setAddress(targetAddress);
     target.setRetries(2);
     target.setTimeout(5000);
     target.setVersion(SnmpConstants.version1);
     PDU pdu = new PDU();
     pdu.add(new VariableBinding(new OID(strOID), new Integer32(Value)));
     pdu.setType(PDU.SET);
     ResponseListener listener =
         new ResponseListener() {
           @Override // public method declared in Object
           public void onResponse(ResponseEvent event) {
             ((Snmp) event.getSource()).cancel(event.getRequest(), this);
             System.out.println("Set Status is:" + event.getResponse().getErrorStatusText());
             // Impresion del status de la respuesta
           }
         };
     snmp.send(pdu, target, null, listener); // envio de parametros
     snmp.close(); // cierra socket snmp
   } catch (Exception e) {
   }
 }
コード例 #20
0
ファイル: SnmpUtil.java プロジェクト: zhangzuoqiang/wnm
 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
ファイル: SnmpUtil.java プロジェクト: zhangzuoqiang/wnm
  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;
  }
コード例 #22
0
ファイル: SnmpBridge.java プロジェクト: nadavwr/jmx2snmp
  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();
    }
  }
コード例 #23
0
  /** {@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;
  }
コード例 #24
0
    /**
     * 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);
          }
        }
      }
    }