Search in sources :

Example 1 with OctetString

use of org.snmp4j.smi.OctetString in project openhab1-addons by openhab.

the class SnmpGenericBindingProvider method parseBindingConfig.

/**
     * Parses a SNMP-OUT configuration by using the regular expression
     * <code>([0-9.a-zA-Z/]+):([0-9.a-zA-Z]+):([0-9.a-zA-Z]+):([0-9]+)</code>.
     * Where the groups should contain the following content:
     * <ul>
     * <li>Command</li>
     * <li>url: ip[/port], port is optional, default: 161</li>
     * <li>[Optional]Version: v1, v2c, v3</li>
     * <li>SNMP community</li>
     * <li>OID</li>
     * <li>Value</li>
     * </ul>
     *
     * Parses a SNMP-IN configuration by using the regular expression
     * <code>([0-9.a-zA-Z/]+):([0-9.a-zA-Z]+):([0-9.a-zA-Z]+):([0-9]+)</code>.
     * Where the groups should contain the following content:
     * <ul>
     * <li>url: ip[/port], port is optional, default: 161</li>
     * <li>[Optional]Version: v1, v2c, v3</li>
     * <li>SNMP community</li>
     * <li>OID</li>
     * <li>Refresh interval (ms)</li>
     * <li>[Optional]transformation rule</li>
     * </ul>
     *
     * Setting refresh interval to 0 will only receive SNMP traps
     *
     * @param config
     *            - the Configuration that needs to be updated with the parsing
     *            results
     * @param item
     *            - the Item that this configuration is intended for
     * @param bindingConfig
     *            - the configuration string that will be parsed
     * @throws BindingConfigParseException
     */
private void parseBindingConfig(SnmpBindingConfig config, Item item, String bindingConfig) throws BindingConfigParseException {
    config.itemType = item.getClass();
    if (bindingConfig != null) {
        // try in without version first
        Matcher inMatcher = IN_BINDING_PATTERN.matcher(bindingConfig);
        if (!inMatcher.matches()) {
            inMatcher = IN_BINDING_PATTERN_TRANSFORM.matcher(bindingConfig);
        }
        if (inMatcher.matches()) {
            SnmpBindingConfigElement newElement = new SnmpBindingConfigElement();
            newElement.address = parseAddress(inMatcher.group(1).toString());
            newElement.snmpVersion = SnmpConstants.version1;
            newElement.community = new OctetString(inMatcher.group(2).toString());
            newElement.oid = new OID(inMatcher.group(3).toString());
            newElement.refreshInterval = Integer.valueOf(inMatcher.group(4)).intValue();
            if (inMatcher.groupCount() == 5) {
                newElement.setTransformationRule(inMatcher.group(5));
            }
            config.put(IN_BINDING_KEY, newElement);
        } else {
            // not matched, try with version
            inMatcher = IN_BINDING_PATTERN_VERSION.matcher(bindingConfig);
            if (!inMatcher.matches()) {
                inMatcher = IN_BINDING_PATTERN_VERSION_TRANSFORM.matcher(bindingConfig);
            }
            if (inMatcher.matches()) {
                SnmpBindingConfigElement newElement = new SnmpBindingConfigElement();
                newElement.address = parseAddress(inMatcher.group(1).toString());
                String version = inMatcher.group(2).toString();
                if (version.equals("v3")) {
                    newElement.snmpVersion = SnmpConstants.version3;
                } else if (version.equals("v2c")) {
                    newElement.snmpVersion = SnmpConstants.version2c;
                } else {
                    newElement.snmpVersion = SnmpConstants.version1;
                }
                newElement.community = new OctetString(inMatcher.group(3).toString());
                newElement.oid = new OID(inMatcher.group(4).toString());
                newElement.refreshInterval = Integer.valueOf(inMatcher.group(5)).intValue();
                if (inMatcher.groupCount() == 6) {
                    newElement.setTransformationRule(inMatcher.group(6));
                }
                config.put(IN_BINDING_KEY, newElement);
            }
        }
        Matcher outMatcher = OUT_BINDING_PATTERN.matcher(bindingConfig);
        if (outMatcher.matches()) {
            SnmpBindingConfigElement newElement = new SnmpBindingConfigElement();
            String commandAsString = outMatcher.group(1).toString();
            newElement.address = parseAddress(outMatcher.group(2).toString());
            newElement.snmpVersion = SnmpConstants.version1;
            newElement.community = new OctetString(outMatcher.group(3).toString());
            newElement.oid = new OID(outMatcher.group(4).toString());
            // Only Integer commands accepted at this time.
            newElement.value = new Integer32(Integer.parseInt(outMatcher.group(5).toString()));
            Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandAsString);
            if (command == null) {
                logger.error("SNMP can't resolve command {} for item {}", commandAsString, item);
            } else {
                config.put(command, newElement);
            }
        } else {
            outMatcher = OUT_BINDING_PATTERN_VERSION.matcher(bindingConfig);
            if (outMatcher.matches()) {
                SnmpBindingConfigElement newElement = new SnmpBindingConfigElement();
                String commandAsString = outMatcher.group(1).toString();
                newElement.address = parseAddress(outMatcher.group(2).toString());
                String version = inMatcher.group(3).toString();
                if (version.equals("v3")) {
                    newElement.snmpVersion = SnmpConstants.version3;
                } else if (version.equals("v2c")) {
                    newElement.snmpVersion = SnmpConstants.version2c;
                } else {
                    newElement.snmpVersion = SnmpConstants.version1;
                }
                newElement.community = new OctetString(outMatcher.group(4).toString());
                newElement.oid = new OID(outMatcher.group(5).toString());
                // Only Integer commands accepted at this time.
                newElement.value = new Integer32(Integer.parseInt(outMatcher.group(6).toString()));
                Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandAsString);
                if (command == null) {
                    logger.error("SNMP can't resolve command {} for item {}", commandAsString, item);
                } else {
                    config.put(command, newElement);
                }
            }
        }
        // have we found any matches?
        if (!outMatcher.matches() && !inMatcher.matches()) {
            throw new BindingConfigParseException(getBindingType() + " binding configuration must consist of four/five/six [config=" + inMatcher + "] or five/six parts [config=" + outMatcher + "]");
        }
    } else {
        return;
    }
}
Also used : OctetString(org.snmp4j.smi.OctetString) Integer32(org.snmp4j.smi.Integer32) Matcher(java.util.regex.Matcher) Command(org.openhab.core.types.Command) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) OID(org.snmp4j.smi.OID) OctetString(org.snmp4j.smi.OctetString)

Example 2 with OctetString

use of org.snmp4j.smi.OctetString in project camel by apache.

the class TrapTest method testSendReceiveTraps.

@Test
public void testSendReceiveTraps() throws Exception {
    // Create a trap PDU
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);
    OID oid = new OID("1.2.3.4.5");
    trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid));
    // put your uptime here
    trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000)));
    trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));
    //Add Payload
    Variable var = new OctetString("some string");
    trap.add(new VariableBinding(oid, var));
    // Send it
    LOG.info("Sending pdu " + trap);
    Endpoint endpoint = context.getEndpoint("direct:snmptrap");
    Exchange exchange = endpoint.createExchange();
    exchange.getIn().setBody(trap);
    Producer producer = endpoint.createProducer();
    producer.process(exchange);
    synchronized (this) {
        Thread.sleep(1000);
    }
    // If all goes right it should come here
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.assertIsSatisfied();
    List<Exchange> exchanges = mock.getExchanges();
    SnmpMessage msg = (SnmpMessage) exchanges.get(0).getIn();
    PDU receivedTrap = msg.getSnmpMessage();
    Assert.assertEquals(trap, receivedTrap);
    if (LOG.isInfoEnabled()) {
        LOG.info("Received SNMP TRAP:");
        Vector<? extends VariableBinding> variableBindings = receivedTrap.getVariableBindings();
        for (VariableBinding vb : variableBindings) {
            LOG.info("  " + vb.toString());
        }
    }
}
Also used : PDU(org.snmp4j.PDU) OctetString(org.snmp4j.smi.OctetString) Variable(org.snmp4j.smi.Variable) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) TimeTicks(org.snmp4j.smi.TimeTicks) OID(org.snmp4j.smi.OID) Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Producer(org.apache.camel.Producer) VariableBinding(org.snmp4j.smi.VariableBinding) Test(org.junit.Test)

Example 3 with OctetString

use of org.snmp4j.smi.OctetString in project mysql_perf_analyzer by yahoo.

the class SNMPClient method getTargetV3.

private Target getTargetV3() {
    //logger.info("Use SNMP v3, "+this.privacyprotocol +"="+this.password+", "+this.privacyprotocol+"="+this.privacypassphrase);
    OID authOID = AuthMD5.ID;
    if ("SHA".equals(this.authprotocol))
        authOID = AuthSHA.ID;
    OID privOID = PrivDES.ID;
    if (this.privacyprotocol == null || this.privacyprotocol.isEmpty())
        privOID = null;
    UsmUser user = new UsmUser(new OctetString(this.username), //auth
    authOID, //auth
    new OctetString(this.password), privOID, //enc
    this.privacypassphrase != null ? new OctetString(this.privacypassphrase) : null);
    snmp.getUSM().addUser(new OctetString(this.username), user);
    Address targetAddress = GenericAddress.parse(address);
    UserTarget target = new UserTarget();
    target.setAddress(targetAddress);
    target.setRetries(2);
    target.setTimeout(1500);
    target.setVersion(this.getVersionInt());
    if (privOID != null)
        target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
    else
        target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
    target.setSecurityName(new OctetString(this.username));
    return target;
}
Also used : OctetString(org.snmp4j.smi.OctetString) Address(org.snmp4j.smi.Address) GenericAddress(org.snmp4j.smi.GenericAddress) OID(org.snmp4j.smi.OID) UserTarget(org.snmp4j.UserTarget) UsmUser(org.snmp4j.security.UsmUser)

Example 4 with OctetString

use of org.snmp4j.smi.OctetString in project mysql_perf_analyzer by yahoo.

the class SNMPClient method start.

/**
	 * 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
	 */
public void start() throws IOException {
    TransportMapping transport = new DefaultUdpTransportMapping();
    snmp = new Snmp(transport);
    if (//add v3 support
    "3".equals(this.version)) {
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
    }
    // Do not forget this line!
    transport.listen();
}
Also used : OctetString(org.snmp4j.smi.OctetString) TransportMapping(org.snmp4j.TransportMapping) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) Snmp(org.snmp4j.Snmp) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) USM(org.snmp4j.security.USM)

Example 5 with OctetString

use of org.snmp4j.smi.OctetString in project mysql_perf_analyzer by yahoo.

the class SNMPClient method getTarget.

/**
	* This method returns a Target, which contains information about
	* where the data should be fetched and how.
	* @return
	*/
private Target getTarget() {
    if ("3".equals(this.version))
        return getTargetV3();
    Address targetAddress = GenericAddress.parse(address);
    CommunityTarget target = new CommunityTarget();
    //logger.info("snmp version "+this.version+", community: "+this.community);
    if (this.community == null || this.community.isEmpty())
        target.setCommunity(new OctetString("public"));
    else
        target.setCommunity(new OctetString(this.community));
    target.setAddress(targetAddress);
    target.setRetries(2);
    target.setTimeout(5000);
    target.setVersion(this.getVersionInt());
    return target;
}
Also used : OctetString(org.snmp4j.smi.OctetString) Address(org.snmp4j.smi.Address) GenericAddress(org.snmp4j.smi.GenericAddress) CommunityTarget(org.snmp4j.CommunityTarget)

Aggregations

OctetString (org.snmp4j.smi.OctetString)40 PDU (org.snmp4j.PDU)17 OID (org.snmp4j.smi.OID)17 Snmp (org.snmp4j.Snmp)14 DefaultUdpTransportMapping (org.snmp4j.transport.DefaultUdpTransportMapping)13 CommunityTarget (org.snmp4j.CommunityTarget)11 ScopedPDU (org.snmp4j.ScopedPDU)11 USM (org.snmp4j.security.USM)11 UdpAddress (org.snmp4j.smi.UdpAddress)11 VariableBinding (org.snmp4j.smi.VariableBinding)11 Test (org.junit.Test)10 UsmUser (org.snmp4j.security.UsmUser)8 Integer32 (org.snmp4j.smi.Integer32)8 ResponseEvent (org.snmp4j.event.ResponseEvent)7 IOException (java.io.IOException)5 TrapInformation (org.opennms.netmgt.snmp.TrapInformation)5 Address (org.snmp4j.smi.Address)5 TimeTicks (org.snmp4j.smi.TimeTicks)5 InetAddress (java.net.InetAddress)4 PDUv1 (org.snmp4j.PDUv1)4