org.snmp4j.smi.OctetString Java Examples

The following examples show how to use org.snmp4j.smi.OctetString. 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: 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 #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: SnmpH3C.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
/**
 * Create SNMP.
 */
private void createSNMP() {

    LOG.info("Creating SNMP...");
    try {
        TransportMapping transport = new DefaultUdpTransportMapping();
        transport.listen();
        snmp = new Snmp(transport);

        // SNMP V3
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);

        LOG.debug("Snmp created.");
        snmp.listen();
        LOG.debug("Snmp listening...");
    } catch (IOException e) {
        throw new RuntimeException("Cannot create snmp!!!", e);
    }
}
 
Example #4
Source File: SnmpH3C.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * @param securityName
 * @param authenticationProtocol   AuthMD5 | AuthSHA
 * @param authenticationPassphrase
 * @param privacyProtocol          PrivDES | PrivAES128 | PrivAES192 | PrivAES256 | Priv3DES | PrivAES
 * @param privacyPassphrase
 * @return
 */
private void createUser(String securityName,
                        AuthGeneric authenticationProtocol, String authenticationPassphrase,
                        PrivacyProtocol privacyProtocol, String privacyPassphrase) {

    this.usmUser = new UsmUser(new OctetString(securityName),
            authenticationProtocol.getID(), new OctetString(authenticationPassphrase),
            privacyProtocol.getID(), new OctetString(privacyPassphrase));
}
 
Example #5
Source File: CommunityIndexCounter32Modifier.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public Map<OID, Variable> getVariableBindings(final OctetString context, final OID queryOID) {
    if (queryOID != null && context != null && context.getValue().length != 0) {
        if (!queryOID.toString().isEmpty() && !context.toString().isEmpty() && communityContextMapping.containsKey(Long.parseLong(context.toString()))) {
            return Collections.singletonMap(queryOID, new Counter32(communityContextMapping.get(Long.parseLong(context.toString()))));
        }
    } else if (queryOID != null) {
        return Collections.singletonMap(queryOID, modify(null));

    }
    return new TreeMap<>();
}
 
Example #6
Source File: CommunityIndexCounter32ModifierTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVariableBindings() {
    final CommunityIndexCounter32Modifier modifier = new CommunityIndexCounter32Modifier();
    modifier.init(modifierProperties);

    final OctetString context1 = new OctetString("20");
    final OID queryOID1 = new OID(OID);
    final Map<OID, Variable> variableBindings1 = modifier.getVariableBindings(context1, queryOID1);

    assertEquals(variableBindings1.size(), 1);
    assertEquals(variableBindings1.get(queryOID1), new Counter32(150L));

    final OctetString context2 = new OctetString("23");
    final OID queryOID2 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings2 = modifier.getVariableBindings(context2, queryOID2);

    assertEquals(variableBindings2.size(), 0, "bindings with not initialized context should be empty");

    final OctetString context3 = null;
    final OID queryOID3 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings3 = modifier.getVariableBindings(context3, queryOID3);

    assertEquals(variableBindings3.size(), 1);
    assertEquals(variableBindings3.get(queryOID3), new Counter32(0L), "bindings with null context should be 0");

    final OctetString context4 = new OctetString();
    final OID queryOID4 = new OID("1.3.6");
    final Map<OID, Variable> variableBindings4 = modifier.getVariableBindings(context4, queryOID4);

    assertEquals(variableBindings4.size(), 1);
    assertEquals(variableBindings4.get(queryOID4), new Counter32(0L), "bindings with empty context should be 0");

    final OctetString context5 = new OctetString("20");
    final OID queryOID5 = null;
    final Map<OID, Variable> variableBindings5 = modifier.getVariableBindings(context5, queryOID5);

    assertEquals(variableBindings5.size(), 0, "bindings with null query OID should be empty");
}
 
Example #7
Source File: SnmpmanSetTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetterForValidValue() throws Exception {
    String newValue = "New interface";
    ResponseEvent responseEvent = setVariableToOID(new OID(OID_OCTETSTRING).append(OID_ROW_INDEX), new OctetString(newValue));
    assertEquals(SnmpConstants.SNMP_ERROR_SUCCESS, responseEvent.getResponse().getErrorStatus());
    assertThatOidHasValue(OID_OCTETSTRING, newValue);
}
 
Example #8
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 #9
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 #10
Source File: SnmpmanAgentTest.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnmpAgentSetupWithCommunityContext() {
    final List<OctetString> contexts = new ArrayList<>();
    final List<SnmpmanAgent> snmpmanAgents = snmpman.getAgents();
    for (final SnmpmanAgent agent : snmpmanAgents) {
        agent.registerManagedObjects();

        contexts.addAll(Arrays.asList(agent.getServer().getContexts()));
    }

    assertTrue(contexts.contains(new OctetString("9")));
    assertTrue(contexts.contains(new OctetString("42")));
}
 
Example #11
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 #12
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 #13
Source File: SNMPUtilsTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create community target
 * @param community community name
 * @param address address
 * @param version SNMP version
 * @return community target
 */
protected static CommunityTarget createCommTarget(String community, String address, int version) {
    CommunityTarget target = new CommunityTarget();
    target.setVersion(version);
    target.setCommunity(new OctetString(community));
    target.setAddress(new UdpAddress(address));
    target.setRetries(0);
    target.setTimeout(500);
    return target;
}
 
Example #14
Source File: SnmpH3C.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * @param address
 * @param securityName  == userName[addUserIntoSNMP] == securityName[createUser]
 * @param securityLevel [NOAUTH_NOPRIV = 1  |  AUTH_NOPRIV = 2  |  AUTH_PRIV = 3] in SecurityLevel
 * @param securityModel 3 (The H3CUserTarget target can only be used with the User Based Security Model (USM))
 *                      //     * @param maxSizeRequestPDU The minimum PDU length is: 484; default: '\uffff'
 * @param version       default: 3
 */
private void createUserTarget(String address, String securityName, int securityLevel, int securityModel,
        /*int maxSizeRequestPDU,*/ int retries, long timeout, int version) {
    userTarget = new UserTarget();
    userTarget.setAddress(GenericAddress.parse("udp:" + address + "/161"));
    userTarget.setSecurityName(new OctetString(securityName));
    userTarget.setSecurityLevel(securityLevel);
    userTarget.setSecurityModel(securityModel);
    userTarget.setRetries(retries);
    userTarget.setTimeout(timeout);
    userTarget.setVersion(version);
}
 
Example #15
Source File: SnmpH3C.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * Add user into SNMP's USM.
 *
 * @param userName
 */
private void addUserIntoSNMP(String userName) {

    if (usmUser != null) {
        if (snmp != null) {
            snmp.getUSM().addUser(new OctetString(userName), this.usmUser);
        } else {
            LOG.error("Please create a instance of SNMP firstly !!");
        }
    } else {
        LOG.error("Please create usmUser before add it into SNMP !!");
    }
}
 
Example #16
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
private PDU createPDU() {
if(!"3".equals(this.version))
	return new PDU();
      ScopedPDU pdu = new ScopedPDU();
      if(this.context != null && !this.context.isEmpty())
        pdu.setContextEngineID(new OctetString(this.context));    //if not set, will be SNMP engine id            
      return pdu;  
  }
 
Example #17
Source File: SNMPUtilsTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create a user target
 * @param address address
 * @param securityLevel security level
 * @param securityName security name
 * @return user target
 */
private static UserTarget createUserTarget(String address, int securityLevel, String securityName) {
    UserTarget target = new UserTarget();
    target.setVersion(SnmpConstants.version3);
    target.setSecurityLevel(securityLevel);
    target.setSecurityName(new OctetString(securityName));
    target.setAddress(new UdpAddress(address));
    target.setRetries(0);
    target.setTimeout(500);
    return target;
}
 
Example #18
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 #19
Source File: SnmpHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private PDU createPDU(SnmpTrapInfo snmpTrapInfo) {
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    int alertType = snmpTrapInfo.getAlertType() + 1;
    if (alertType > 0) {
        long sysUpTimeTicks = ManagementFactory.getRuntimeMXBean().getUptime() / 10;
        trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(sysUpTimeTicks)));
        trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, getOID(CsSnmpConstants.TRAPS_PREFIX + alertType)));
        if (snmpTrapInfo.getDataCenterId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.DATA_CENTER_ID), new UnsignedInteger32(snmpTrapInfo.getDataCenterId())));
        }

        if (snmpTrapInfo.getPodId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.POD_ID), new UnsignedInteger32(snmpTrapInfo.getPodId())));
        }

        if (snmpTrapInfo.getClusterId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.CLUSTER_ID), new UnsignedInteger32(snmpTrapInfo.getClusterId())));
        }

        if (snmpTrapInfo.getMessage() != null) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.MESSAGE), new OctetString(snmpTrapInfo.getMessage())));
        } else {
            throw new CloudRuntimeException(" What is the use of alert without message ");
        }

        if (snmpTrapInfo.getGenerationTime() != null) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME), new OctetString(snmpTrapInfo.getGenerationTime().toString())));
        } else {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME)));
        }
    } else {
        throw new CloudRuntimeException(" Invalid alert Type ");
    }

    return trap;
}
 
Example #20
Source File: SNMPUtilsTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create a user target
 * @param address address
 * @param securityLevel security level
 * @param securityName security name
 * @return user target
 */
private static UserTarget createUserTarget(String address, int securityLevel, String securityName) {
    UserTarget target = new UserTarget();
    target.setVersion(SnmpConstants.version3);
    target.setSecurityLevel(securityLevel);
    target.setSecurityName(new OctetString(securityName));
    target.setAddress(new UdpAddress(address));
    target.setRetries(0);
    target.setTimeout(500);
    return target;
}
 
Example #21
Source File: SNMPUtilsTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Method to create community target
 * @param community community name
 * @param address address
 * @param version SNMP version
 * @return community target
 */
protected static CommunityTarget createCommTarget(String community, String address, int version) {
    CommunityTarget target = new CommunityTarget();
    target.setVersion(version);
    target.setCommunity(new OctetString(community));
    target.setAddress(new UdpAddress(address));
    target.setRetries(0);
    target.setTimeout(500);
    return target;
}
 
Example #22
Source File: SnmpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @{inheritDoc
 */
@Override
public OctetString getCommunity(String itemName, Command command) {
    SnmpBindingConfig config = (SnmpBindingConfig) bindingConfigs.get(itemName);
    return config != null ? config.get(command).community : new OctetString();
}
 
Example #23
Source File: SnmpGenericBindingProvider.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @{inheritDoc
 */
@Override
public OctetString getCommunity(String itemName) {
    SnmpBindingConfig config = (SnmpBindingConfig) bindingConfigs.get(itemName);
    return config != null ? config.get(IN_BINDING_KEY).community : new OctetString();
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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;
}