当前位置: 首页>>代码示例>>Java>>正文


Java Snmp类代码示例

本文整理汇总了Java中org.snmp4j.Snmp的典型用法代码示例。如果您正苦于以下问题:Java Snmp类的具体用法?Java Snmp怎么用?Java Snmp使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Snmp类属于org.snmp4j包,在下文中一共展示了Snmp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setUpTarget

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * Helper method that initializes the snmp target to listening mode. This
 * method is explicitly for V1 and V2 messages. This method will create and
 * set up the TransportMapping and target for SNMP V1 and V2. It creates a
 * TransportMapping and puts it in the listening mode. Also Creates
 * CommunityTarget object and sets SNMP target properties.
 *
 * @param communityName
 *            Community name of the target
 * @param targetIP
 *            IP address of Target machine
 * @param portNumber
 *            Port number
 * @return The Target created
 * @throws IOException
 *             IOException
 */
private Target setUpTarget( final String communityName, final String targetIP, final int portNumber )
        throws IOException
{
    final InetAddress inetAddress = InetAddress.getByName( targetIP );
    final Address address = new UdpAddress( inetAddress, portNumber );
    final OctetString community = new OctetString( communityName );
    final TransportMapping transport = new DefaultUdpTransportMapping();
    snmp = new Snmp( transport );
    snmp.listen();

    // Creating the communityTarget object and setting its properties
    final CommunityTarget communityTarget = new CommunityTarget();
    communityTarget.setCommunity( community );
    // TODO Needs to check also for v2 messages
    communityTarget.setVersion( SnmpConstants.version1 );
    communityTarget.setAddress( address );
    // TODO Need to confirm, whether this value needs to be configures
    communityTarget.setRetries( SnmpManager.DEFAULT_RETRIES );
    // TODO Need to confirm, whether this value needs to be configures
    communityTarget.setTimeout( SnmpManager.DEFAULT_TIMEOUT );
    return communityTarget;
}
 
开发者ID:Comcast,项目名称:cats,代码行数:40,代码来源:SnmpManagerImpl.java

示例2: main

import org.snmp4j.Snmp; //导入依赖的package包/类
public static void main(String[] args) throws IOException, InterruptedException {
    Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.listen();

    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(new UdpAddress("23.23.52.11/161"));
    target.setTimeout(3000);    //3s
    target.setRetries(1);

    PDU pdu = new PDU();
    pdu.setType(PDU.GETBULK);
    pdu.setMaxRepetitions(1); 
    pdu.setNonRepeaters(0);
    VariableBinding[] array = {new VariableBinding(new OID("1.3.6.1.4.1.2000.1.2.5.1.3")),
                               new VariableBinding(new OID("1.3.6.1.4.1.2000.1.3.1.1.7")),
                               new VariableBinding(new OID("1.3.6.1.4.1.2000.1.3.1.1.10")),
                               new VariableBinding(new OID("1.3.6.1.4.1.2000.1.2.5.1.19"))};
    pdu.addAll(array);

    //pdu.add(new VariableBinding(new OID("1.3.6.1.4.1.2000.1.2.5.1.3"))); 

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();

    if (response == null) {
	    System.out.println("TimeOut...");
    } else {
	    if (response.getErrorStatus() == PDU.noError) {
               Vector<? extends VariableBinding> vbs = response.getVariableBindings();
               for (VariableBinding vb : vbs) {
                   System.out.println(vb.getVariable().toString());
	        }
	    } else {
	        System.out.println("Error:" + response.getErrorStatusText());
	    }
    }
}
 
开发者ID:javiroman,项目名称:flume-snmp-source,代码行数:40,代码来源:testSNMPGetBulk.java

示例3: sendTrap

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * Send next-in-line trap from queue to to SNMP server
 */
public void sendTrap() {
	
	String trapVal = trapQueue.poll();
	if (trapVal == null) {
		return;
	}

	try {
		PDUv1 trapPdu = createTrapPDU(trapVal);	    	
		DefaultUdpTransportMapping tm = new DefaultUdpTransportMapping();
		Snmp snmp = new Snmp(tm);
		tm.listen();
		OctetString community = new OctetString(SNMP_XAP_COMMUNITY);
		Address add = GenericAddress.parse("udp" + ":" + snmpServerIP + "/" + snmpServerPort);
		CommunityTarget target = new CommunityTarget(add, community);
		target.setVersion(SnmpConstants.version1);
		target.setRetries(0);
		target.setTimeout(5000);		
		snmp.send(trapPdu, target);  
	} 
	catch (IOException e) {
		e.printStackTrace();
	} 
}
 
开发者ID:Gigaspaces,项目名称:xap-openspaces,代码行数:28,代码来源:SnmpTrapSender.java

示例4: snmpGet

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * 获取指定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;
}
 
开发者ID:DevopsJK,项目名称:SuitAgent,代码行数:26,代码来源:SNMPHelper.java

示例5: snmpWalk

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:DevopsJK,项目名称:SuitAgent,代码行数:42,代码来源:SNMPHelper.java

示例6: onResponse

import org.snmp4j.Snmp; //导入依赖的package包/类
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);

    // check for valid response
    if (event.getRequest() == null || event.getResponse() == null) {
        // ignore null requests/responses
        LOG.debug("Received invalid SNMP event. Request: " + event.getRequest() + " / Response: " + event.getResponse());
        return;
    }
    
    PDU pdu = event.getResponse();
    processPDU(pdu);
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:17,代码来源:SnmpOIDPoller.java

示例7: start

import org.snmp4j.Snmp; //导入依赖的package包/类
@Override
public void start() {
    // Initialize the connection to the external client
    try {
        snmp = new Snmp(new DefaultUdpTransportMapping());
        snmp.listen();

        target = new CommunityTarget();
        target.setCommunity(new OctetString("public"));
        target.setVersion(SnmpConstants.version2c);
        target.setAddress(new UdpAddress(bindAddress + "/" + bindPort));
        target.setTimeout(3000);    //3s
        target.setRetries(1);

        pdu.setType(PDU.GETBULK);
        pdu.setMaxRepetitions(1); 
        pdu.setNonRepeaters(0);

    } catch (IOException ex) {
        //
    }

    super.start();
}
 
开发者ID:javiroman,项目名称:flume-snmp-source,代码行数:25,代码来源:SNMPQuerySource.java

示例8: sendTest

import org.snmp4j.Snmp; //导入依赖的package包/类
public void sendTest(String agentAddress, int port, String community, PDU pdu) {
    for (RegistrationInfo info : s_registrations.values()) {
        if (port == info.getPort()) {
            Snmp snmp = info.getSession();
            MessageDispatcher dispatcher = snmp.getMessageDispatcher();
            TransportMapping transport = info.getTransportMapping();
            
            int securityModel = (pdu instanceof PDUv1 ? SecurityModel.SECURITY_MODEL_SNMPv1 :SecurityModel.SECURITY_MODEL_SNMPv2c);
            int messageModel = (pdu instanceof PDUv1 ? MessageProcessingModel.MPv1 : MessageProcessingModel.MPv2c);
            CommandResponderEvent e = new CommandResponderEvent(dispatcher, transport, new IpAddress(agentAddress), messageModel, 
                                                                securityModel, community.getBytes(), 
                                                                SecurityLevel.NOAUTH_NOPRIV, new PduHandle(), pdu, 1000, null);

            info.getHandler().processPdu(e);
        }
    }

}
 
开发者ID:qoswork,项目名称:opennmszh,代码行数:19,代码来源:Snmp4JStrategy.java

示例9: sendTrapV2

import org.snmp4j.Snmp; //导入依赖的package包/类
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();
}
 
开发者ID:Stratio,项目名称:ingestion,代码行数:27,代码来源:SNMPUtils.java

示例10: startUp

import org.snmp4j.Snmp; //导入依赖的package包/类
@Override
public void startUp() throws IOException {
	log.info("Snmp Trap Receiver Start");
	log.info("listened on " + Configure.getInstance().getUdpTrapIpPort());
	ThreadPool pool = ThreadPool.create(Const.THREAD_POOL_NAME, Const.AGENT_THREAD_NUM);
	MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(pool, new MessageDispatcherImpl());
	Address listenAddress = GenericAddress.parse(Configure.getInstance().getUdpTrapIpPort());
	TransportMapping transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress);
	// ����SNMP������ʹ�俪ʼ����
	Snmp snmp = new Snmp(dispatcher, transport);
       snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
       snmp.listen();
       snmp.addCommandResponder(new CommandResponderImpl());
}
 
开发者ID:wangzijian777,项目名称:snmpTool,代码行数:15,代码来源:SnmpReceiver.java

示例11: start

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * 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();

	if (SNMPversion == 3) {
		USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
		SecurityModels.getInstance().addSecurityModel(usm);
	}
	snmp = new Snmp(transport);

	if (SNMPversion == 3)
		snmp.getUSM().addUser(new OctetString(ver3Username),
				new UsmUser(new OctetString(ver3Username), AuthMD5.ID, new OctetString(ver3AuthPasscode), null, null));

	// Do not forget this line!
	transport.listen();
}
 
开发者ID:dana-i2cat,项目名称:opennaas-routing-nfv,代码行数:24,代码来源:SNMPManager.java

示例12: init

import org.snmp4j.Snmp; //导入依赖的package包/类
private void init() throws UnknownHostException, IOException {
	threadPool = ThreadPool.create("Trap", 4);
	dispatcher = new MultiThreadedMessageDispatcher(threadPool,
			new MessageDispatcherImpl());

	listenAddress = GenericAddress.parse("udp:0.0.0.0/"
			+ SnmpPref.getTrapsPort());
	DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping(
			(UdpAddress) listenAddress);
	snmp = new Snmp(dispatcher, transport);
	snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
	snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
	snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
	USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
			MPv3.createLocalEngineID()), 0);
	SecurityModels.getInstance().addSecurityModel(usm);
	snmp.listen();
	logger.debug("Listening for traps on "
			+ transport.getListenAddress().toString());
}
 
开发者ID:ccascone,项目名称:JNetMan,代码行数:21,代码来源:SnmpTrapReceiver.java

示例13: testTrapReceiverWithoutOpenNMS

import org.snmp4j.Snmp; //导入依赖的package包/类
public void testTrapReceiverWithoutOpenNMS() throws Exception {
    System.out.println("SNMP4J: Register for Traps");
    trapCount = 0;
    Snmp snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(9162)));
    snmp.addCommandResponder(this);
    snmp.getUSM().addUser(
            new OctetString("opennmsUser"),
            new UsmUser(new OctetString("opennmsUser"), AuthMD5.ID, new OctetString("0p3nNMSv3"), PrivDES.ID, new OctetString("0p3nNMSv3")));
    snmp.listen();

    sendTraps();

    System.out.println("SNMP4J: Unregister for Traps");
    snmp.close();

    System.out.println("SNMP4J: Checking Trap status");
    assertEquals(2, trapCount);
}
 
开发者ID:vishwaabhinav,项目名称:OpenNMS,代码行数:19,代码来源:Snmp4jTrapReceiverTest.java

示例14: createSnmpSession

import org.snmp4j.Snmp; //导入依赖的package包/类
public Snmp createSnmpSession() throws IOException {
    TransportMapping transport = new DefaultUdpTransportMapping();
    Snmp session = new Snmp(transport);
    
    if (isSnmpV3()) {
        // Make a new USM
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
        // Add the specified user to the USM
        usm.addUser(
            getSecurityName(),
            new UsmUser(
                getSecurityName(),
                getAuthProtocol(),
                getAuthPassPhrase(),
                getPrivProtocol(),
                getPrivPassPhrase()
            )
        );
        // Remove the old SNMPv3 MessageProcessingModel. If you don't do this, you'll end up with
        // two SNMPv3 MessageProcessingModel instances in the dispatcher and connections will fail.
        MessageProcessingModel oldModel = session.getMessageDispatcher().getMessageProcessingModel(MessageProcessingModel.MPv3);
        if (oldModel != null) {
            session.getMessageDispatcher().removeMessageProcessingModel(oldModel);
        }
        // Add a new SNMPv3 MessageProcessingModel with the newly-created USM
        session.getMessageDispatcher().addMessageProcessingModel(new MPv3(usm));
    }
    
    return session;
}
 
开发者ID:vishwaabhinav,项目名称:OpenNMS,代码行数:31,代码来源:Snmp4JAgentConfig.java

示例15: SNMPV3Session

import org.snmp4j.Snmp; //导入依赖的package包/类
/**
 * 创建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);
}
 
开发者ID:DevopsJK,项目名称:SuitAgent,代码行数:44,代码来源:SNMPV3Session.java


注:本文中的org.snmp4j.Snmp类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。