org.snmp4j.Snmp Java Examples

The following examples show how to use org.snmp4j.Snmp. 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: SnmpHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public SnmpHelper(String address, String community) {
    _target = new CommunityTarget();
    _target.setCommunity(new OctetString(community));
    _target.setVersion(SnmpConstants.version2c);
    _target.setAddress(new UdpAddress(address));
    try {
        _snmp = new Snmp(new DefaultUdpTransportMapping());
    } catch (IOException e) {
        _snmp = null;
        throw new CloudRuntimeException(" Error in crearting snmp object, " + e.getMessage());
    }
}
 
Example #2
Source File: SnmpAlarmProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
@Deactivate
public void deactivate(ComponentContext context) {
    for (Map.Entry<Integer, Snmp> entry : portSessionMap.entrySet()) {
        try {
            entry.getValue().close();
        } catch (IOException e) {
            log.warn("Can't close SNMP notification session on Ip {} and Port {}",
                     localIp, entry.getKey(), e);
        }
    }
    mastershipService.addListener(mastershipListener);
    deviceService.removeListener(deviceListener);
    providerRegistry.unregister(this);
    providerService = null;
    log.info("Stopped");
}
 
Example #3
Source File: AbstractSNMPProcessor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Builds target resource.
 * @param context Process context
 */
private void buildTargetResource(ProcessContext context) {
    if((this.transportMapping == null) || !this.transportMapping.isListening() || (this.snmp == null)) {
        try {
            this.transportMapping = new DefaultUdpTransportMapping();
            this.snmp = new Snmp(this.transportMapping);

            if("SNMPv3".equals(context.getProperty(SNMP_VERSION).getValue())) {
                USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
                SecurityModels.getInstance().addSecurityModel(usm);
            }

            this.transportMapping.listen();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to initialize UDP transport mapping", e);
        }
    }
    if (this.snmpTarget == null) {
        this.snmpTarget = this.createSnmpTarget(context);
    }
    if (this.targetResource == null) {
        this.targetResource = this.finishBuildingTargetResource(context);
    }
}
 
Example #4
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定OID的 get
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGet(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();
    if(response == null){
        log.warn("response null - error:{} peerAddress:{} source:{} request:{}",
                responseEvent.getError(),
                responseEvent.getPeerAddress(),
                responseEvent.getSource(),
                responseEvent.getRequest());
    }
    return response;
}
 
Example #5
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 #6
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定OID的 get
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGet(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();
    if(response == null){
        log.warn("response null - error:{} peerAddress:{} source:{} request:{}",
                responseEvent.getError(),
                responseEvent.getPeerAddress(),
                responseEvent.getSource(),
                responseEvent.getRequest());
    }
    return response;
}
 
Example #7
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves static object value.
 *
 * @param handler parent driver handler
 * @param oid object identifier
 * @return the variable
 * @throws IOException if unable to retrieve the object value
 */
public static Variable get(DriverHandler handler, String oid) throws IOException {
    List<VariableBinding> vbs = new ArrayList<>();
    vbs.add(new VariableBinding(new OID(oid)));
    PDU pdu = new PDU(PDU.GET, vbs);
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    ResponseEvent event = session.send(pdu, target);
    return event.getResponse().get(0).getVariable();
}
 
Example #8
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 #9
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 #10
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 4 votes vote down vote up
public static void sendTrapV1(String port) throws IOException {

        TransportMapping<?> transport = new DefaultUdpTransportMapping();
        transport.listen();

        CommunityTarget comtarget = new CommunityTarget();
        comtarget.setCommunity(new OctetString(new OctetString("public")));
        comtarget.setVersion(SnmpConstants.version1);
        comtarget.setAddress(new UdpAddress("127.0.0.1/" + port));
        comtarget.setRetries(2);
        comtarget.setTimeout(5000);

        PDU trap = new PDUv1();
        trap.setType(PDU.V1TRAP);

        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));

        // Send
        Snmp snmp = new Snmp(transport);
        snmp.send(trap, comtarget);
        transport.close();
        snmp.close();

    }
 
Example #11
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 4 votes vote down vote up
/**
 * 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("3".equals(this.version))//add v3 support
	{
		USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);  
		SecurityModels.getInstance().addSecurityModel(usm);  
	}
	// Do not forget this line!
	transport.listen();
}
 
Example #12
Source File: SNMPV3Session.java    From OpenFalcon-SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * 创建SNMPV3会话
 * @param userInfo
 * @throws IOException
 * @throws AgentArgumentException
 */
public SNMPV3Session(SNMPV3UserInfo userInfo) throws IOException, AgentArgumentException {
    if(StringUtils.isEmpty(userInfo.getAddress())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议的访问地址不能为空");
    }
    if(StringUtils.isEmpty(userInfo.getUsername())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议的访问用户名不能为空");
    }
    if(!StringUtils.isEmpty(userInfo.getAythType()) && StringUtils.isEmpty(userInfo.getAuthPswd())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议指定了认证算法 aythType,就必须要指定认证密码");
    }
    if(!StringUtils.isEmpty(userInfo.getPrivType()) && StringUtils.isEmpty(userInfo.getPrivPswd())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议指定了加密算法 privType,就必须要指定加密密码");
    }

    this.userInfo = userInfo;
    snmp = new Snmp(new DefaultUdpTransportMapping());
    USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
    SecurityModels.getInstance().addSecurityModel(usm);
    snmp.listen();

    UsmUser user = new UsmUser(
            new OctetString(userInfo.getUsername()),
            getAuthProtocol(userInfo.getAythType()), new OctetString(userInfo.getAuthPswd()),
            getPrivProtocol(userInfo.getPrivType()), new OctetString(userInfo.getPrivPswd()));

    snmp.getUSM().addUser(new OctetString(userInfo.getUsername()), user);

    target = new UserTarget();
    target.setSecurityName(new OctetString(userInfo.getUsername()));
    target.setVersion(SnmpConstants.version3);
    target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
    target.setAddress(GenericAddress.parse(userInfo.getProtocol() + ":" + userInfo.getAddress() + "/" + userInfo.getPort()));
    target.setTimeout(8000);
    target.setRetries(1);
}
 
Example #13
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}
 
Example #14
Source File: SnmpmanSetTest.java    From snmpman with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
public void initSnmpSession() throws IOException {
    snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.listen();
}
 
Example #15
Source File: ProcessMessage.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public void onResponse(ResponseEvent re) {
       // 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.
       try {
            Object source = re.getSource();

           // test to ignore REPORTS from DISCOVERY messages in SNMPv3
           if (!(source instanceof Snmp)) return;

           ((Snmp) source).cancel(re.getRequest(), this);

           //create the SnmpMsg received
           MsgSnmp msg = new MsgSnmp(listenpoint.getStack());
           msg.setPdu(re.getResponse());
           
           //TODO: how to know the version here to set communityTarget or UserTarget
           Target target = new CommunityTarget();
//           ((CommunityTarget)target).setCommunity(new OctetString(re.getStateReference().getSecurityName()));
           target.setAddress(re.getPeerAddress());
           msg.setTarget((AbstractTarget)target);
           UdpAddress add = (UdpAddress) re.getPeerAddress();
           msg.setRemotePort(add.getPort());
           msg.setRemoteHost(add.getInetAddress().getHostAddress());
           msg.setListenpoint(listenpoint);

           StackFactory.getStack(StackFactory.PROTOCOL_SNMP).receiveMessage(msg);
       } catch (Exception ex) {
       }
    }
 
Example #16
Source File: ListenpointSnmp.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean create(String protocol) throws Exception
{
    processMessage = new ProcessMessage(this);
    snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(getHost() + "/" + getPort())));
    snmp.addCommandResponder(processMessage);

    // TEST CODE : initialize for receiving SNMPV3
    {
        String authPassword = stack.getConfig().getString("protocol.authPassword");
        String encryptPassword = stack.getConfig().getString("protocol.encryptPassword");

        snmp.getMessageDispatcher().removeMessageProcessingModel(new MPv3());
        snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3(MPv3.createLocalEngineID(new OctetString(this.getUID()))));

        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(this.getUID().getBytes()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);

        // need to get a list of users and their params from config
        snmp.getUSM().addUser(new OctetString("MD5DES"),
                new UsmUser(new OctetString("MD5DES"),
                            AuthMD5.ID, new OctetString("protocol.authPassword"),
                            PrivDES.ID, new OctetString("protocol.encryptPassword")));
    }

    snmp.listen();

    return true;
}
 
Example #17
Source File: SNMPV3Session.java    From SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * 创建SNMPV3会话
 * @param userInfo
 * @throws IOException
 * @throws AgentArgumentException
 */
public SNMPV3Session(SNMPV3UserInfo userInfo) throws IOException, AgentArgumentException {
    if(StringUtils.isEmpty(userInfo.getAddress())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议的访问地址不能为空");
    }
    if(StringUtils.isEmpty(userInfo.getUsername())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议的访问用户名不能为空");
    }
    if(!StringUtils.isEmpty(userInfo.getAythType()) && StringUtils.isEmpty(userInfo.getAuthPswd())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议指定了认证算法 aythType,就必须要指定认证密码");
    }
    if(!StringUtils.isEmpty(userInfo.getPrivType()) && StringUtils.isEmpty(userInfo.getPrivPswd())){
        throw new AgentArgumentException("SNMPV3Session创建失败:snmp v3协议指定了加密算法 privType,就必须要指定加密密码");
    }

    this.userInfo = userInfo;
    snmp = new Snmp(new DefaultUdpTransportMapping());
    USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID(
            new OctetString(HostUtil.getHostIp() + UUID.randomUUID().toString())
    )), 0);
    SecurityModels.getInstance().addSecurityModel(usm);
    snmp.listen();

    UsmUser user = new UsmUser(
            new OctetString(userInfo.getUsername()),
            getAuthProtocol(userInfo.getAythType()), new OctetString(userInfo.getAuthPswd()),
            getPrivProtocol(userInfo.getPrivType()), new OctetString(userInfo.getPrivPswd()));

    snmp.getUSM().addUser(new OctetString(userInfo.getUsername()), user);

    target = new UserTarget();
    target.setSecurityName(new OctetString(userInfo.getUsername()));
    target.setVersion(SnmpConstants.version3);
    target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
    target.setAddress(GenericAddress.parse(userInfo.getProtocol() + ":" + userInfo.getAddress() + "/" + userInfo.getPort()));
    target.setTimeout(TIMEOUT);
    target.setRetries(1);
}
 
Example #18
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}
 
Example #19
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 #20
Source File: AbstractSNMPProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Builds target resource.
 * @param context Process context
 */
private void buildTargetResource(ProcessContext context) {
    if((this.transportMapping == null) || !this.transportMapping.isListening() || (this.snmp == null)) {
        try {
            this.transportMapping = new DefaultUdpTransportMapping();
            this.snmp = new Snmp(this.transportMapping);

            if("SNMPv3".equals(context.getProperty(SNMP_VERSION).getValue())) {
                USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
                SecurityModels.getInstance().addSecurityModel(usm);
            }

            this.transportMapping.listen();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to initialize UDP transport mapping", e);
        }
    }
    if (this.snmpTarget == null) {
        this.snmpTarget = this.createSnmpTarget(context);
    }
    if (this.targetResource == null) {
        this.targetResource = this.finishBuildingTargetResource(context);
    }
}
 
Example #21
Source File: SnmpBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Called when a response from a GET is received
 *
 * @see org.snmp4j.event.ResponseListener#onResponse(org.snmp4j.event.ResponseEvent )
 */
@Override
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);

    dispatchPdu(event.getPeerAddress(), event.getResponse());
}
 
Example #22
Source File: SNMPUtilsTest.java    From nifi with Apache License 2.0 3 votes vote down vote up
/**
 * Method to prepare user target and to add id in the User Based Security Model of the given SNMP instance
 * @param snmp SNMP instance
 * @param address address
 * @param securityLevel security level
 * @param securityName security name
 * @param auth authentication protocol
 * @param priv private protocol
 * @param authPwd authentication password
 * @param privPwd private password
 * @return user target
 */
protected static UserTarget prepareUser(Snmp snmp, String address, int securityLevel, String securityName, OID auth, OID priv, String authPwd, String privPwd) {
    snmp.getUSM().removeAllUsers();
    OctetString aPwd = authPwd != null ? new OctetString(authPwd) : null;
    OctetString pPwd = privPwd != null ? new OctetString(privPwd) : null;
    snmp.getUSM().addUser(new OctetString(securityName), new UsmUser(new OctetString(securityName), auth, aPwd, priv, pPwd));
    return createUserTarget(address, securityLevel, securityName);
}
 
Example #23
Source File: DefaultSnmpDevice.java    From onos with Apache License 2.0 3 votes vote down vote up
@Override
public Snmp getSession() {
    return session;
}
 
Example #24
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Sends a synchronous SET request to the supplied target.
 *
 * @param handler parent driver handler
 * @param vbs a list of variable bindings
 * @return the response event
 * @throws IOException if unable to set the target
 */
public static ResponseEvent set(DriverHandler handler, List<? extends VariableBinding> vbs) throws IOException {
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    PDU pdu = new PDU(PDU.SET, vbs);
    return session.set(pdu, target);
}
 
Example #25
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 #26
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieves a table.
 *
 * @param handler parent driver handler
 * @param columnOIDs column oid object identifiers
 * @return the table
 * @throws IOException if unable to retrieve the object value
 */
public static List<TableEvent> getTable(DriverHandler handler, OID[] columnOIDs) throws IOException {
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    TableUtils tableUtils = new TableUtils(session, new DefaultPDUFactory());
    return tableUtils.getTable(target, columnOIDs, null, null);
}
 
Example #27
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 3 votes vote down vote up
private static Snmp getSession(DriverHandler handler) {
    Snmp session = getDevice(handler).getSession();
    return session;
}
 
Example #28
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 #29
Source File: SNMPUtilsTest.java    From localization_nifi with Apache License 2.0 3 votes vote down vote up
/**
 * Method to create an instance of SNMP
 * @return instance of SNMP
 * @throws IOException IO Exception
 */
protected static Snmp createSnmp() throws IOException {
    DefaultUdpTransportMapping transportMapping = new DefaultUdpTransportMapping();
    transportMapping.listen();
    return new Snmp(transportMapping);
}
 
Example #30
Source File: PolatisSnmpUtility.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Sends a SET request.
 *
 * @param handler parent driver handler
 * @param pdu SNMP protocol data unit
 * @return the response event
 * @throws IOException if unable to send a set request
 */
public static ResponseEvent set(DriverHandler handler, PDU pdu) throws IOException {
    Snmp session = getSession(handler);
    CommunityTarget target = getTarget(handler);
    return session.set(pdu, target);
}