如何将自定义陷阱消息发送给snmp管理器?

时间:2014-09-11 14:51:35

标签: java snmp net-snmp snmp4j

在下面的代码中添加我的自定义动态消息

描述:

我的管理器运行时提到了NOCIP,也有MIB文件但是在发送特定OID的陷阱时,消息应该有所不同,尽管陷阱对于不同的场景是相同的

例如:

if(...){

trap1:自定义message1

}

否则如果(...){

trap1:自定义message2

}

否则{

trap2:自定义message3

}

public void sendSnmpV2Trap()
  {
    try
    {
      //Create Transport Mapping
      TransportMapping transport = new DefaultUdpTransportMapping();
      transport.listen();

      //Create Target
      CommunityTarget comtarget = new CommunityTarget();
      comtarget.setCommunity(new OctetString(community));
      comtarget.setVersion(SnmpConstants.version2c);
      comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
      comtarget.setRetries(2);
      comtarget.setTimeout(5000);

      //Create PDU for V2
      PDU pdu = new PDU();

      // need to specify the system up time
      pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new OctetString(new Date().toString())));
      pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(trapOid)));
      pdu.add(new VariableBinding(SnmpConstants.snmpTrapAddress, new IpAddress(ipAddress)));


      pdu.setType(PDU.NOTIFICATION);

      //Send the PDU
      Snmp snmp = new Snmp(transport);
      System.out.println("Sending V2 Trap to " + ipAddress + " on Port " + port);
      snmp.send(pdu, comtarget);
      snmp.close();
    }
    catch (Exception e)
    {
      System.err.println("Error in Sending V2 Trap to " + ipAddress + " on Port " + port);
      System.err.println("Exception Message = " + e.getMessage());
    }
  }
}-

1 个答案:

答案 0 :(得分:1)

如果您希望陷阱包含自定义消息,则应将其作为VariableBinding附加。

例如,如果要传递OctetString,则执行

pdu.add(new VariableBinding(<yourCustomOID>, new OctetString("This unit has caught fire")));

将其添加到添加了三个已存在的变量的代码之后。确保varbinds的顺序与MIB文件所宣传的顺序相匹配。

我会尝试将if-else逻辑分解为一个单独的方法,并让它为OctetString(或者你发送的任何内容)返回适当的值。

相关问题