Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19796
  • 博文数量: 16
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 100
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-04 10:47
文章分类
文章存档

2012年(16)

我的朋友
最近访客

分类:

2012-03-04 10:55:52

原文地址:SNMP4J 收发trap 编程 作者:zhengdong1987

  • SNMP4J 发SNMPV1 TRAP 和 SNMPV2 TRAP
1.先建立一个工具类,主要是对SNMP,TARGET,PDU的三个SNMP4J基本类的实例化
参见上篇文章:<专业级的SNMP框架---SNMP4J>
      
      public static PDU createPDU(int pduType) {
          
          PDU request;

          if (pduType == PDU.V1TRAP) {
            request = new PDUv1();   
          }
          else {
            request = new PDU();
          }
          
          request.setType(pduType);
          return request;
    }


2.定义Snmp Engine,负责维护基本的Snmp连接
参见上篇文章:<专业级的SNMP框架---SNMP4J>

3.发SNMPV1 TRAP 和 SNMPV2 TRAP
public class TrapSendTest {
   
    private static Logger log = Logger.getLogger(TrapSendTest.class);
   

    public static void sendv1Trap(String host,String community
            ,String customOid,String customString) throws IOException  {
       
        // 初始化,建立snmp对象和target对象
        SnmpV1V2cEngine engine = new SnmpV1V2cEngine(host,community,SnmpConstants.version1);
       
        // 建立PDU对象
        PDUv1 request = (PDUv1)Snmp4JHelper.createPDU(PDU.V1TRAP);
       
        // 发起snmp request
        request.add(new VariableBinding(new OID(customOid), new OctetString(customString)));

        engine.sendRequest(request);

        engine.finalize();
       
    }
    public static void sendv2Trap(String host,String community
                    ,String customOid,String customString) throws IOException{
       
        // 初始化,建立snmp对象和target对象
        SnmpV1V2cEngine engine = new SnmpV1V2cEngine(host,community,SnmpConstants.version2c);
       
        // 建立PDU对象
        PDU request = Snmp4JHelper.createPDU(PDU.TRAP);
       
        // 1.let uptime just be system time...
        TimeTicks sysUpTime = new TimeTicks((long)(System.currentTimeMillis()/1000));
        request.add(new VariableBinding(SnmpConstants.sysUpTime, sysUpTime));
       
        // 2.define snmp trap OID
        OID trapOID = SnmpConstants.coldStart;
        request.add(new VariableBinding(SnmpConstants.snmpTrapOID, trapOID));
       
        // 3. define custom oid
        request.add(new VariableBinding(new OID(customOid), new OctetString(customString)));
       
        // 发起snmp request
        engine.sendRequest(request);

       
        engine.finalize();
    }
 
    public static void main(String[] args) throws IOException {

        String host = "192.168.0.111/162";
        String community = "public";
        String customOid = "1.3.6.1.2.99.999";
        String customString = "hello world";   
       
       
        sendv1Trap(host,community,customOid,customString);
        sendv2Trap(host,community,customOid,customString);

    }

4.看测试结果:
[root@oracle ~]# /etc/init.d/snmptrapd start
启动 snmptrapd:[  确定  ]
执行上面的程序

[root@oracle ~]# tail -f /var/log/messages
Nov 20 07:44:21 oracle sshd(pam_unix)[3664]: session opened for user root by root(uid=0)
Nov 20 10:17:32 oracle sshd(pam_unix)[4153]: authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.0.101  user=root
Nov 20 10:17:38 oracle sshd(pam_unix)[4155]: session opened for user root by root(uid=0)
Nov 20 11:51:41 oracle sshd(pam_unix)[4202]: session opened for user root by root(uid=0)
Nov 20 11:51:58 oracle snmpd: snmpd 启动 succeeded
Nov 20 11:51:58 oracle snmpd[4246]: [init_smux] bind failed: Address already in use
Nov 20 11:51:58 oracle snmpd[4246]: Error opening specified endpoint "udp:161"
Nov 20 11:51:58 oracle snmpd[4246]: Server Exiting with code 1
Nov 20 11:52:21 oracle snmptrapd[4255]: 2010-11-20 11:52:21 NET-SNMP version 5.1.2 Started.
Nov 20 11:52:21 oracle snmptrapd: snmptrapd 启动 succeeded
Nov 20 11:52:49 oracle snmptrapd[4255]: 2010-11-20 11:52:49 0.0.0.0(via 192.168.0.100) TRAP, SNMP v1, community public  SNMPv2-SMI::zeroDotZero Cold Start Trap (0) Uptime: 0:00:00.00      SNMPv2-SMI::mgmt.99.999 = STRING: "hello world"
Nov 20 11:52:50 oracle snmptrapd[4255]: 2010-11-20 11:52:50 192.168.0.100 [192.168.0.100]: SNMPv2-MIB::sysUpTime.0 = Timeticks: (1290343653) 149 days, 8:17:16.53   SNMPv2-MIB::snmpTrapOID.0 = OID: SNMPv2-MIB::coldStart  SNMPv2-SMI::mgmt.99.999 = STRING: "hello world"


  • SNMP4J LISTEN 收TRAP
public class Trapreceiver implements CommandResponder {
   
      private Address address;
      private OctetString community = new OctetString("public");
   
      public Trapreceiver(String IPAddress,String community) throws IOException{
          this.address = Snmp4JHelper.getAddress(IPAddress);
          this.community = Snmp4JHelper.createOctetString(community);
          listen();
      }
    
     
      public synchronized void listen() throws IOException {
         
          int numDispatcherThreads = 2;
         
          AbstractTransportMapping transport;
            if (address instanceof TcpAddress) {
              transport = new DefaultTcpTransportMapping((TcpAddress) address);
            }
            else {
              transport = new DefaultUdpTransportMapping((UdpAddress) address);
            }
           
           
            ThreadPool threadPool =
                ThreadPool.create("DispatcherPool", numDispatcherThreads);
            MessageDispatcher mtDispatcher =
                new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());

            // add message processing models
            mtDispatcher.addMessageProcessingModel(new MPv1());
            mtDispatcher.addMessageProcessingModel(new MPv2c());
            mtDispatcher.addMessageProcessingModel(new MPv3());

            // add all security protocols
            SecurityProtocols.getInstance().addDefaultProtocols();

            Snmp snmp = new Snmp(mtDispatcher, transport);
           
            CommunityTarget target = new CommunityTarget();
            target.setCommunity(community);
           
            snmp.addCommandResponder(this);

            transport.listen();
            System.out.println("Listening on "+address);

            try {
              this.wait();
            }
            catch (InterruptedException ex) {
            }
           
           
        }
 
    
    @Override
     public synchronized void processPdu(CommandResponderEvent e) {
        PDU command = e.getPDU();
        if (command != null) {
         
          System.out.println(command.toString());
         
          if ((command.getType() != PDU.TRAP) &&
              (command.getType() != PDU.V1TRAP) &&
              (command.getType() != PDU.REPORT) &&
              (command.getType() != PDU.RESPONSE)) {
           
            command.setErrorIndex(0);
            command.setErrorStatus(0);
            command.setType(PDU.RESPONSE);
            StatusInformation statusInformation = new StatusInformation();
            StateReference ref = e.getStateReference();
           
            try {
              e.getMessageDispatcher().returnResponsePdu(e.
                                                         getMessageProcessingModel(),
                                                         e.getSecurityModel(),
                                                         e.getSecurityName(),
                                                         e.getSecurityLevel(),
                                                         command,
                                                         e.getMaxSizeResponsePDU(),
                                                         ref,
                                                         statusInformation);
            }
            catch (MessageException ex) {
              System.err.println("Error while sending response: "+ex.getMessage());
              LogFactory.getLogger(Snmp4jModel.class).error(ex);
            }
          }
        }
      }
    public static void main(String[] args) throws Exception {
       
        String host = "192.168.0.101/162";
        String community = "public";
       
        new Trapreceiver(host,community);
   
    }
测试:
执行程序
Listening on 192.168.0.101/162
可以看到端口被监听
D:\Documents and Settings\mac>netstat -an

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:21             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:22             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING
  UDP    0.0.0.0:161            *:*
  UDP    0.0.0.0:445            *:*
  UDP    0.0.0.0:500            *:*
  UDP    0.0.0.0:1025           *:*
  UDP    0.0.0.0:1031           *:*
  UDP    192.168.0.101:162      *:*
执行上面的发trap程序TrapSendTest.java,注意将地址改成"192.168.0.111/162"
Listening on 192.168.0.101/162
V1TRAP[reqestID=0,timestamp=0:00:00.00,enterprise=0.0,genericTrap=0,specificTrap=0, VBS[1.3.6.1.2.99.999 = hello world]]
TRAP[requestID=864057064, errorStatus=Success(0), errorIndex=0, VBS[1.3.6.1.2.1.1.3.0 = 149 days, 8:35:58.43; 1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.6.3.1.1.5.1; 1.3.6.1.2.99.999 = hello world]]
 
阅读(686) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~