org.snmp4j.smi.Address Java Examples

The following examples show how to use org.snmp4j.smi.Address. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SnmpBinding.java    From openhab1-addons with Eclipse Public License 2.0 8 votes vote down vote up
/**
 * Will be called whenever a {@link PDU} is received on the given port
 * specified in the listen() method. It extracts a {@link Variable}
 * according to the configured OID prefix and sends its value to the event
 * bus.
 */
@Override
public void processPdu(CommandResponderEvent event) {
    Address addr = event.getPeerAddress();
    if (addr == null) {
        return;
    }

    String s = addr.toString().split("/")[0];
    if (s == null) {
        logger.error("TRAP: failed to translate address {}", addr);
        dispatchPdu(addr, event.getPDU());
    } else {
        // Need to change the port to 161, which is what the bindings are configured for since
        // at least some SNMP devices send traps from a random port number. Otherwise the trap
        // won't be found as the address check will fail. It feels like there should be a better
        // way to do this!!!
        Address address = GenericAddress.parse("udp:" + s + "/161");
        dispatchPdu(address, event.getPDU());
    }
}
 
Example #2
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
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),  
			authOID, new OctetString(this.password),  //auth
			privOID, this.privacypassphrase!=null?new OctetString(this.privacypassphrase):null); //enc
	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;
}
 
Example #3
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
* 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;
}
 
Example #4
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
public static void sendTrapV2(String port) throws IOException {
    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)));
    trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));

    // Add Payload
    Variable var = new OctetString("some string");
    trap.add(new VariableBinding(oid, var));

    // Specify receiver
    Address targetaddress = new UdpAddress("127.0.0.1/" + port);
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(targetaddress);

    // Send
    Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.send(trap, target, null, null);

    snmp.close();
}
 
Example #5
Source File: SnmpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private Address parseAddress(String s) throws BindingConfigParseException {
    String addressString = s.contains("/") ? s : s + "/161";
    Address address = GenericAddress.parse("udp:" + addressString);
    if (address == null) {
        throw new BindingConfigParseException(getBindingType() + " binding configuration address is invalid: " + s);
    }
    return address;
}
 
Example #6
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 5 votes vote down vote up
private static CommunityTarget getTarget(DriverHandler handler) {
    SnmpDevice device = getDevice(handler);
    Address targetAddress = GenericAddress.parse(device.getProtocol() +
                                                 ":" + device.getSnmpHost() +
                                                 "/" + device.getSnmpPort());
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString(getDevice(handler).getCommunity()));
    target.setAddress(targetAddress);
    target.setRetries(3);
    target.setTimeout(1000L * 3L);
    target.setVersion(SnmpConstants.version2c);
    target.setMaxSizeRequestPDU(MAX_SIZE_RESPONSE_PDU);
    return target;
}
 
Example #7
Source File: AbstractSnmpmanTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
static CommunityTarget getCommunityTarget(String community, Address targetAddress) {
    final CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString(community));
    target.setAddress(targetAddress);
    target.setRetries(2);
    target.setTimeout(1500);
    target.setVersion(SnmpConstants.version2c);
    return target;
}
 
Example #8
Source File: SnmpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @{inheritDoc
 */
@Override
public Address getAddress(String itemName, Command command) {
    SnmpBindingConfig config = (SnmpBindingConfig) bindingConfigs.get(itemName);
    return config != null ? config.get(command).address : null;
}
 
Example #9
Source File: SnmpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @{inheritDoc
 */
@Override
public Address getAddress(String itemName) {
    SnmpBindingConfig config = (SnmpBindingConfig) bindingConfigs.get(itemName);
    return config != null ? config.get(IN_BINDING_KEY).address : null;
}
 
Example #10
Source File: SnmpBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private void dispatchPdu(Address address, PDU pdu) {
    if (pdu != null & address != null) {
        logger.debug("Received PDU from '{}' '{}'", address, pdu);
        for (SnmpBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                // Check the IP address
                if (!provider.getAddress(itemName).equals(address)) {
                    continue;
                }

                // Check the OID
                OID oid = provider.getOID(itemName);
                Variable variable = pdu.getVariable(oid);
                if (variable != null) {
                    Class<? extends Item> itemType = provider.getItemType(itemName);

                    // Do any transformations
                    String value = variable.toString();
                    try {
                        value = provider.doTransformation(itemName, value);
                    } catch (TransformationException e) {
                        logger.error("Transformation error with item {}: {}", itemName, e);
                    }

                    // Change to a state
                    State state = null;
                    if (itemType.isAssignableFrom(StringItem.class)) {
                        state = StringType.valueOf(value);
                    } else if (itemType.isAssignableFrom(NumberItem.class)) {
                        state = DecimalType.valueOf(value);
                    } else if (itemType.isAssignableFrom(SwitchItem.class)) {
                        state = OnOffType.valueOf(value);
                    }

                    if (state != null) {
                        eventPublisher.postUpdate(itemName, state);
                    } else {
                        logger.debug("'{}' couldn't be parsed to a State. Valid State-Types are String and Number",
                                variable.toString());
                    }
                } else {
                    logger.trace("PDU doesn't contain a variable with OID '{}'", oid.toString());
                }
            }
        }
    }
}
 
Example #11
Source File: AbstractSnmpmanTest.java    From snmpman with Apache License 2.0 4 votes vote down vote up
public static List<TableEvent> getResponse(final OID query, int port, final String community) throws Exception {
    final Address targetAddress = GenericAddress.parse(String.format("127.0.0.1/%d", port));
    final Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.listen();

    final CommunityTarget target = getCommunityTarget(community, targetAddress);

    // creating PDU
    final PDUFactory pduFactory = new DefaultPDUFactory(PDU.GETBULK);
    final TableUtils utils = new TableUtils(snmp, pduFactory);

    return utils.getTable(target, new OID[]{query}, null, null);
}
 
Example #12
Source File: LumentumSnmpDevice.java    From onos with Apache License 2.0 4 votes vote down vote up
private void createDevice(String ipAddress, int port) throws IOException {
    Address targetAddress = GenericAddress.parse("udp:" + ipAddress + "/" + port);
    TransportMapping transport = new DefaultUdpTransportMapping();
    transport.listen();
    snmp = new Snmp(transport);

    // setting up target
    target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setAddress(targetAddress);
    target.setRetries(3);
    target.setTimeout(1000L * 3L);
    target.setVersion(SnmpConstants.version2c);
    target.setMaxSizeRequestPDU(MAX_SIZE_RESPONSE_PDU);
}
 
Example #13
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 4 votes vote down vote up
public static void sendTrapV3(String port) {
    try {
        Address targetAddress = GenericAddress.parse("udp:127.0.0.1/" + port);
        TransportMapping<?> transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
                MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
        transport.listen();

        snmp.getUSM().addUser(new OctetString("MD5DES"),
                new UsmUser(new OctetString("MD5DES"), null, null, null, null));

        // Create Target
        UserTarget target = new UserTarget();
        target.setAddress(targetAddress);
        target.setRetries(1);
        target.setTimeout(11500);
        target.setVersion(SnmpConstants.version3);
        target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
        target.setSecurityName(new OctetString("MD5DES"));

        // Create PDU for V3
        ScopedPDU pdu = new ScopedPDU();
        pdu.setType(ScopedPDU.NOTIFICATION);
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime));
        pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, SnmpConstants.linkDown));
        pdu.add(new VariableBinding(new OID("1.2.3.4.5"), new OctetString("Major")));

        // Send the PDU
        snmp.send(pdu, target);

        transport.close();
        snmp.close();
    } catch (Exception e) {
        System.err.println("Error in Sending Trap to (IP:Port)=> " + "127.0.0.1" + ":" + port);
        System.err.println("Exception Message = " + e.getMessage());
    }
}
 
Example #14
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 3 votes vote down vote up
public static void sendTrapV3AuthPriv(String port) throws IOException {
    try {
        Address targetAddress = GenericAddress.parse("udp:127.0.0.1/" + port);
        TransportMapping<?> transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
                MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
        transport.listen();

        snmp.getUSM().addUser(
                new OctetString("user"),
                new UsmUser(new OctetString("user"), AuthMD5.ID, new OctetString("12345678"),
                        PrivDES.ID, new OctetString("passphrase")));

        // Create Target
        UserTarget target = new UserTarget();
        target.setAddress(targetAddress);
        target.setRetries(1);
        target.setTimeout(11500);
        target.setVersion(SnmpConstants.version3);
        target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
        target.setSecurityName(new OctetString("user"));

        // Create PDU for V3
        ScopedPDU pdu = new ScopedPDU();
        pdu.setType(ScopedPDU.NOTIFICATION);
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime));
        pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, SnmpConstants.linkDown));
        pdu.add(new VariableBinding(new OID("1.2.3.4.5"), new OctetString("Major")));

        // Send the PDU
        snmp.send(pdu, target);

        transport.close();
        snmp.close();
    } catch (Exception e) {
        System.err.println("Error in Sending Trap to (IP:Port)=> " + "127.0.0.1" + ":" + port);
        System.err.println("Exception Message = " + e.getMessage());
    }
}
 
Example #15
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 3 votes vote down vote up
public static void sendTrapV3Auth(String port) throws IOException {
    try {
        Address targetAddress = GenericAddress.parse("udp:127.0.0.1/" + port);
        TransportMapping<?> transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
                MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
        transport.listen();

        snmp.getUSM().addUser(
                new OctetString("user"),
                new UsmUser(new OctetString("user"), AuthMD5.ID, new OctetString("12345678"),
                        null, null));

        // Create Target
        UserTarget target = new UserTarget();
        target.setAddress(targetAddress);
        target.setRetries(1);
        target.setTimeout(11500);
        target.setVersion(SnmpConstants.version3);
        target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
        target.setSecurityName(new OctetString("user"));

        // Create PDU for V3
        ScopedPDU pdu = new ScopedPDU();
        pdu.setType(ScopedPDU.NOTIFICATION);
        pdu.add(new VariableBinding(SnmpConstants.sysUpTime));
        pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, SnmpConstants.linkDown));
        pdu.add(new VariableBinding(new OID("1.2.3.4.5"), new OctetString("Major")));

        // Send the PDU
        snmp.send(pdu, target);

        transport.close();
        snmp.close();
    } catch (Exception e) {
        System.err.println("Error in Sending Trap to (IP:Port)=> " + "127.0.0.1" + ":" + port);
        System.err.println("Exception Message = " + e.getMessage());
    }
}
 
Example #16
Source File: SnmpBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns the IP address of the SNMP binding
 * 
 * @return address for SNMP binding
 */
Address getAddress(String itemName);
 
Example #17
Source File: SnmpBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 votes vote down vote up
Address getAddress(String itemName, Command command);