Example #1
0
  private PDU sendRequestV1V2(PDU pdu, int version) throws Exception {
    PDU response;
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setAddress(new UdpAddress(m_agent.getInetAddress(), m_agent.getPort()));
    target.setVersion(version);
    if (m_timeout > 0) {
      target.setTimeout(m_timeout);
    }

    TransportMapping<UdpAddress> transport = null;
    try {
      transport = new DefaultUdpTransportMapping();
      Snmp snmp = new Snmp(transport);
      transport.listen();

      ResponseEvent e = snmp.send(pdu, target);
      response = e.getResponse();
    } finally {
      if (transport != null) {
        transport.close();
      }
    }
    return response;
  }
  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();
  }
  /**
   * Start the Snmp session. If you forget the listen() method you will not get any answers because
   * the communication is asynchronous and the listen() method listens for answers.
   *
   * @throws IOException
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  private void start() throws IOException {
    TransportMapping transport = new DefaultUdpTransportMapping();
    snmp = new Snmp(transport);
    USM usm =
        new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(usm);
    transport.listen();

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

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

    // Target
    CommunityTarget target = CreateAndSetTarget();

    // PDU
    PDU pdu = CreateAndSetPdu();

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

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

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

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

        if (errorStatus == PDU.noError) {
          readResponse(responsePdu.getVariableBindings());
          // System.out.println(responsePdu.getVariableBindings().getClass());
          // System.out.println("SNMP get response: " + responsePdu.getVariableBindings());
        } else {
          System.out.println("Error: Request Failed");
          System.out.println("Error Status: " + errorStatus);
          System.out.println("Error Index: " + errorIndex);
          System.out.println("Error Status Text: " + errorStatusText);
        }
      } else {
        System.out.println("Error: PDU response is null");
      }
    } else {
      System.out.println("Error: Agent Timeout");
    }
    snmp.close();
  }
Example #6
0
  private PDU sendRequestV3(PDU pdu) throws IOException {
    PDU response;

    OctetString userId = new OctetString("opennmsUser");
    OctetString pw = new OctetString("0p3nNMSv3");

    UserTarget target = new UserTarget();
    target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
    target.setSecurityName(userId);
    target.setAddress(new UdpAddress(m_agent.getInetAddress(), m_agent.getPort()));
    target.setVersion(SnmpConstants.version3);
    if (m_timeout > 0) {
      target.setTimeout(m_timeout);
    } else {
      target.setTimeout(5000);
    }

    TransportMapping<UdpAddress> transport = null;
    try {
      USM usm =
          new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
      SecurityModels.getInstance().addSecurityModel(usm);
      transport = new DefaultUdpTransportMapping();
      Snmp snmp = new Snmp(transport);

      UsmUser user = new UsmUser(userId, AuthMD5.ID, pw, PrivDES.ID, pw);
      snmp.getUSM().addUser(userId, user);

      transport.listen();

      ResponseEvent e = snmp.send(pdu, target);
      response = e.getResponse();
    } finally {
      if (transport != null) {
        transport.close();
      }
    }
    return response;
  }
Example #7
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);

  }
 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) {
   }
 }
 /**
  * Start the Snmp session. If you forget the listen() method you will not get any answers because
  * the communication is asynchronous and the listen() method listens for answers.
  *
  * @throws IOException
  */
 private void start() throws IOException {
   TransportMapping transport = new DefaultUdpTransportMapping();
   snmp = new Snmp(transport);
   // Do not forget this line!
   transport.listen();
 }
  public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setNrErrors(1);
    result.setResult(false);

    String servername = environmentSubstitute(serverName);
    int nrPort = Const.toInt(environmentSubstitute("" + port), DEFAULT_PORT);
    String Oid = environmentSubstitute(oid);
    int timeOut = Const.toInt(environmentSubstitute("" + timeout), DEFAULT_TIME_OUT);
    int retry = Const.toInt(environmentSubstitute("" + nrretry), 1);
    String messageString = environmentSubstitute(message);

    Snmp snmp = null;

    try {
      TransportMapping transMap = new DefaultUdpTransportMapping();
      snmp = new Snmp(transMap);

      UdpAddress udpAddress = new UdpAddress(InetAddress.getByName(servername), nrPort);
      ResponseEvent response = null;
      if (targettype.equals(target_type_Code[0])) {
        // Community target
        String community = environmentSubstitute(comString);

        CommunityTarget target = new CommunityTarget();
        PDUv1 pdu1 = new PDUv1();
        transMap.listen();

        target.setCommunity(new OctetString(community));
        target.setVersion(SnmpConstants.version1);
        target.setAddress(udpAddress);
        if (target.getAddress().isValid()) {
          if (log.isDebug()) {
            logDebug("Valid IP address");
          }
        } else {
          throw new KettleException("Invalid IP address");
        }
        target.setRetries(retry);
        target.setTimeout(timeOut);

        // create the PDU
        pdu1.setGenericTrap(6);
        pdu1.setSpecificTrap(PDUv1.ENTERPRISE_SPECIFIC);
        pdu1.setEnterprise(new OID(Oid));
        pdu1.add(new VariableBinding(new OID(Oid), new OctetString(messageString)));

        response = snmp.send(pdu1, target);

      } else {
        // User target
        String userName = environmentSubstitute(user);
        String passPhrase = environmentSubstitute(passphrase);
        String engineID = environmentSubstitute(engineid);

        UserTarget usertarget = new UserTarget();
        transMap.listen();
        usertarget.setAddress(udpAddress);
        if (usertarget.getAddress().isValid()) {
          if (log.isDebug()) {
            logDebug("Valid IP address");
          }
        } else {
          throw new KettleException("Invalid IP address");
        }

        usertarget.setRetries(retry);
        usertarget.setTimeout(timeOut);
        usertarget.setVersion(SnmpConstants.version3);
        usertarget.setSecurityLevel(SecurityLevel.AUTH_PRIV);
        usertarget.setSecurityName(new OctetString("MD5DES"));

        // Since we are using SNMPv3 we use authenticated users
        // this is handled by the UsmUser and USM class

        UsmUser uu =
            new UsmUser(
                new OctetString(userName),
                AuthMD5.ID,
                new OctetString(passPhrase),
                PrivDES.ID,
                new OctetString(passPhrase));

        USM usm = snmp.getUSM();

        if (usm == null) {
          throw new KettleException("Null Usm");
        } else {
          usm =
              new USM(
                  SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
          usm.addUser(new OctetString(userName), uu);
          if (log.isDebug()) {
            logDebug("Valid Usm");
          }
        }

        // create the PDU
        ScopedPDU pdu = new ScopedPDU();
        pdu.add(new VariableBinding(new OID(Oid), new OctetString(messageString)));
        pdu.setType(PDU.TRAP);
        if (!Const.isEmpty(engineID)) {
          pdu.setContextEngineID(new OctetString(engineID));
        }

        // send the PDU
        response = snmp.send(pdu, usertarget);
      }

      if (response != null) {
        if (log.isDebug()) {
          logDebug("Received response from: " + response.getPeerAddress() + response.toString());
        }
      }

      result.setNrErrors(0);
      result.setResult(true);
    } catch (Exception e) {
      logError(BaseMessages.getString(PKG, "JobEntrySNMPTrap.ErrorGetting", e.getMessage()));
    } finally {
      try {
        if (snmp != null) {
          snmp.close();
        }
      } catch (Exception e) {
        /* Ignore */
      }
    }

    return result;
  }
Example #11
0
 //    @Override
 public void stop() throws IOException {
   transport.close();
 }
Example #12
0
 //    @Override
 public void start() throws IOException {
   transport.listen();
 }
Example #13
0
  /**
   * Starts the <code>MockSnmpAgent</code> running. Meant to be called from the <code>start</code>
   * method of class <code>Thread</code>, but could also be used to bring up a standalone mock
   * agent.
   *
   * @see org.snmp4j.agent.BaseAgent#run()
   * @author Jeff Gehlbach
   */
  @Override
  public void run() {
    s_log.info("MockSnmpAgent: Initializing SNMP Agent");
    try {
      init();
      s_log.info("MockSnmpAgent: Finished 'init' loading config");
      loadConfig(ImportModes.UPDATE_CREATE);
      s_log.info("MockSnmpAgent: finished 'loadConfig' adding shutdown hook");
      addShutdownHook();
      s_log.info("MockSnmpAgent: finished 'addShutdownHook' finishing init");
      finishInit();
      s_log.info("MockSnmpAgent: finished 'finishInit' running agent");
      super.run();
      s_log.info("MockSnmpAgent: finished running Agent - setting running to true");
      m_running.set(true);
    } catch (final BindException e) {
      s_log.error(
          String.format(
              "MockSnmpAgent: Unable to bind to %s.  You probably specified an invalid address or a port < 1024 and are not running as root. Exception: %s",
              m_address.get(), e),
          e);
    } catch (final Throwable t) {
      s_log.error("MockSnmpAgent: An error occurred while initializing: " + t, t);
      t.printStackTrace();
    }

    boolean interrupted = false;
    s_log.info(
        "MockSnmpAgent: Initialization Complete processing message until agent is shutdown.");
    while (m_running.get()) {
      try {
        Thread.sleep(10); // fast, Fast, FAST, *FAST*!!!
      } catch (final InterruptedException e) {
        interrupted = true;
        break;
      }
    }

    s_log.info("MockSnmpAgent: Shutdown called stopping agent.");
    for (final TransportMapping transportMapping : transportMappings) {
      try {
        if (transportMapping != null) {
          transportMapping.close();
        }
      } catch (final IOException t) {
        s_log.error(
            "MockSnmpAgent: an error occurred while closing the transport mapping "
                + transportMapping
                + ": "
                + t,
            t);
      }
    }

    m_stopped.set(true);

    s_log.info("MockSnmpAgent: Agent is no longer running.");
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }