예제 #1
0
  /**
   * Runs a sample agent with a default configuration defined by <code>SampleAgentConfig.properties
   * </code>. A sample command line is:
   *
   * <pre>
   * -c SampleAgent.cfg -bc SampleAgent.bc udp:127.0.0.1/4700 tcp:127.0.0.1/4700
   * </pre>
   *
   * @param args the command line arguments defining at least the listen addresses. The format is
   *     <code>-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}]
   *    +ts[s] +cfg[s] #address[s<(udp|tcp):.*[/[0-9]+]?>] ..</code>. For the format description see
   *     {@link ArgumentParser}.
   */
  public static void main(String[] args) {
    ArgumentParser parser =
        new ArgumentParser(
            "-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}] " + "+ts[s] +cfg[s]",
            "#address[s<(udp|tcp):.*[/[0-9]+]?>] ..");
    Map commandLineParameters = null;
    try {
      args = new String[1];
      args[0] = "udp:127.0.0.1/4700";
      commandLineParameters = parser.parse(args);
      SampleAgent sampleAgent = new SampleAgent(commandLineParameters);
      // Add all available security protocols (e.g.
      // SHA,MD5,DES,AES,3DES,..)
      SecurityProtocols.getInstance().addDefaultProtocols();
      // configure system group:
      // Set system description:
      // sampleAgent.agent.getSysDescr().setValue("My system
      // description".getBytes());
      // Set system OID (= OID of the AGENT-CAPABILITIES statement
      // describing
      // the implemented MIB objects of this agent:
      // sampleAgent.agent.getSysOID().setValue("1.3.1.6.1.4.1....");
      // Set the system services
      // sampleAgent.agent.getSysServices().setValue(72);
      sampleAgent.run();

    } catch (ParseException ex) {
      System.err.println(ex.getMessage());
    }
  }
예제 #2
0
 @Override
 public void addUser(Snmp snmp) {
   USM usm =
       new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
   SecurityModels.getInstance().addSecurityModel(usm);
   if (engineId != null) snmp.setLocalEngine(engineId.getValue(), 0, 0);
   snmp.getUSM()
       .addUser(
           securityName,
           new UsmUser(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase));
 }
예제 #3
0
  /** {@inheritDoc} */
  @Override
  protected void initMessageDispatcher() {
    s_log.info("MockSnmpAgent: starting initMessageDispatcher()");
    try {
      dispatcher = new MessageDispatcherImpl();

      usm =
          new USM(SecurityProtocols.getInstance(), agent.getContextEngineID(), updateEngineBoots());

      mpv3 = new MPv3(usm);

      SecurityProtocols.getInstance().addDefaultProtocols();
      dispatcher.addMessageProcessingModel(new MPv1());
      dispatcher.addMessageProcessingModel(new MPv2c());
      dispatcher.addMessageProcessingModel(mpv3);
      initSnmpSession();
    } finally {
      s_log.info("MockSnmpAgent: finished initMessageDispatcher()");
    }
  }
  /**
   * 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());
  }
예제 #5
0
  @Before
  public void setUp() throws Exception {
    // Create a global USM that all client calls will use
    MPv3.setEnterpriseID(5813);
    m_usm =
        new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(m_usm);

    m_agent =
        MockSnmpAgent.createAgentAndRun(
            classPathResource("penrose-lldp-mib.properties"), "127.0.0.1/1691");

    m_requestedVarbinds = new ArrayList<AnticipatedRequest>();
  }
    /** This method will listen for traps and response pdu's from SNMP agent. */
    public synchronized void listen(TransportIpAddress address) throws IOException {
      AbstractTransportMapping transport;

      if (address instanceof TcpAddress) {
        transport = new DefaultTcpTransportMapping((TcpAddress) address);
      } else {
        transport = new DefaultUdpTransportMapping((UdpAddress) address);
      }

      ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
      MessageDispatcher mtDispatcher =
          new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());

      // add message processing models
      mtDispatcher.addMessageProcessingModel(new MPv1());
      mtDispatcher.addMessageProcessingModel(new MPv2c());

      // add all security protocols
      SecurityProtocols.getInstance().addDefaultProtocols();
      SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());

      // Create Target
      CommunityTarget target = new CommunityTarget();
      target.setCommunity(new OctetString("public"));

      Snmp snmp = new Snmp(mtDispatcher, transport);
      snmp.addCommandResponder(this);

      transport.listen();
      logger.info("Listening on " + address);

      try {
        this.wait();
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }
    }
예제 #7
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;
  }
예제 #8
0
  @Before
  public void setUp() throws Exception {
    // Create a global USM that all client calls will use
    SNMP4JSettings.setEnterpriseID(5813);
    m_usm =
        new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(m_usm);

    try {
      m_agent =
          MockSnmpAgent.createAgentAndRun(
              classPathResource("penrose-lldp-mib.properties"),
              str(InetAddress.getLocalHost()) + "/0");
    } catch (Throwable e) {
      m_agent =
          MockSnmpAgent.createAgentAndRun(
              classPathResource("penrose-lldp-mib.properties"),
              str(InetAddressUtils.ONE_TWENTY_SEVEN) + "/0");
    }

    m_requestedVarbinds = new ArrayList<AnticipatedRequest>();
  }
예제 #9
0
  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;
  }