public void initComm() throws IOException {

    // 设置管理进程的IP和端口
    targetAddress = GenericAddress.parse("udp:192.168.0.91/162");
    TransportMapping transport = new DefaultUdpTransportMapping();
    snmp = new Snmp(transport);
    transport.listen();
  }
 /**
  * This method returns a Target, which contains information about where the data should be fetched
  * and how.
  *
  * @return
  */
 private Target getTarget() {
   Address targetAddress = GenericAddress.parse(address);
   CommunityTarget target = new CommunityTarget();
   target.setCommunity(new OctetString("public"));
   target.setAddress(targetAddress);
   target.setRetries(2);
   target.setTimeout(1500);
   target.setVersion(SnmpConstants.version2c);
   return target;
 }
Esempio n. 3
0
 /**
  * 创建共同体对象communityTarget
  *
  * @param address
  * @param community
  * @return CommunityTarget
  */
 public static CommunityTarget createMyDefaultTarget(String address, String community) {
   Address targetAddress = GenericAddress.parse(address);
   CommunityTarget target = new CommunityTarget();
   target.setCommunity(new OctetString(community));
   target.setAddress(targetAddress);
   target.setVersion(DEFAULT_VERSION);
   target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
   target.setRetries(DEFAULT_RETRY);
   return target;
 }
 /**
  * 创建对象communityTarget
  *
  * @param ip
  * @param community
  * @return CommunityTarget
  */
 public static CommunityTarget createDefault(String ip, String community) {
   Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT);
   CommunityTarget target = new CommunityTarget();
   target.setCommunity(new OctetString(community));
   target.setAddress(address);
   target.setVersion(DEFAULT_VERSION);
   target.setTimeout(DEFAULT_TIMEOUT); // milliseconds
   target.setRetries(DEFAULT_RETRY);
   return target;
 }
Esempio n. 5
0
 protected void addListenAddresses(MessageDispatcher md, List addresses) {
   for (Iterator it = addresses.iterator(); it.hasNext(); ) {
     Address address = GenericAddress.parse((String) it.next());
     TransportMapping tm = TransportMappings.getInstance().createTransportMapping(address);
     if (tm != null) {
       md.addTransportMapping(tm);
     } else {
       logger.warn("No transport mapping available for address '" + address + "'.");
     }
   }
 }
Esempio n. 6
0
 private Target getTarget(String strCommunity) {
   if (m_target == null) {
     Address addr = GenericAddress.parse("udp:" + getHost() + "/" + getPort());
     m_target = new CommunityTarget();
     m_target.setCommunity(new OctetString(strCommunity));
     m_target.setAddress(addr);
     m_target.setVersion(SnmpConstants.version1);
     m_target.setRetries(3);
   }
   return m_target;
 }
Esempio n. 7
0
 private void createSession() throws IOException {
   if (snmp == null) {
     Address address = GenericAddress.parse(deviceAddress);
     AbstractTransportMapping transport;
     if (address instanceof TlsAddress) {
       transport = new TLSTM();
     } else if (address instanceof TcpAddress) {
       transport = new DefaultTcpTransportMapping();
     } else {
       transport = new DefaultUdpTransportMapping();
     }
     // Could save some CPU cycles:
     transport.setAsyncMsgProcessingSupported(false);
     snmp = new Snmp(transport);
     snmp.listen();
     if (getSnmpVersion() == SnmpConstants.version3) {
       snmp.getUSM()
           .addUser(
               new OctetString("user"),
               new UsmUser(
                   new OctetString("user"),
                   AuthMD5.ID,
                   new OctetString("user"),
                   AuthMD5.ID,
                   null));
       // create the target
       target = new UserTarget();
       target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
       target.setSecurityName(new OctetString("user"));
     } else {
       // create the target
       target = new CommunityTarget();
       ((CommunityTarget) target).setCommunity(new OctetString(configuration.getReadCommunity()));
     }
     target.setAddress(address);
     target.setVersion(getSnmpVersion());
     target.setRetries(retries);
     target.setTimeout(timeout);
   }
 }
  /**
   * 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;
  }
Esempio n. 9
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;
  }
 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) {
   }
 }
Esempio n. 11
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;
  }
Esempio n. 12
0
 /**
  * 创建共同体对象communityTarget
  *
  * @param address
  * @param community
  * @param version
  * @param timeOut
  * @param retry
  * @return CommunityTarget
  */
 public static CommunityTarget createCommunityTarget(
     String address, String community, int version, long timeOut, int retry) {
   Address targetAddress = GenericAddress.parse(address);
   return createCommunityTarget(targetAddress, community, version, timeOut, retry);
 }
Esempio n. 13
0
 /**
  * 创建 UserTarget
  *
  * @param address
  * @param version
  * @param timeOut
  * @param level
  * @param securityName
  * @return UserTarget
  */
 public static UserTarget createUserTarget(
     String address, int version, long timeOut, int level, String securityName) {
   Address targetAddress = GenericAddress.parse(address);
   return createUserTarget(targetAddress, version, timeOut, level, securityName);
 }
Esempio n. 14
0
 /**
  * 创建snmp Address
  *
  * @param protocol
  * @param ip
  * @param port
  * @return Address
  */
 public static Address createAddress(String protocol, String ip, int port) {
   String address = protocol + ":" + ip + "/" + port;
   return GenericAddress.parse(address);
 }
Esempio n. 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);
  }