NetSnmp初步(二):發送Notification


前面提到了程序要主動上報異常狀況,snmp提供了notification機制來實現此功能。大致步驟如下:

1.還是從MIB文件開始:
在文件"/usr/local/share/snmp/mibs/FIGURE-IT-MIB.txt"增加如下內容:

 1 recordNotification NOTIFICATION-TYPE
2 OBJECTS { recordTrapsEntry }
3 STATUS current
4 DESCRIPTION
5 "Record's notifications "
6 ::= { record 2 }
7
8 recordTrapsEntry OBJECT-TYPE
9 -- SYNTAX SnmpAdminString
10 SYNTAX OCTET STRING (SIZE(1..512))
11 MAX-ACCESS accessible-for-notify
12 STATUS current
13 DESCRIPTION
14 "Record's notifications entery."
15 ::= { recordNotification 1 }

通過snmptranslate -IR -Tp record命令檢查mib文件是否添加正確。

2.使用mib2c生成代碼:
#sudo mib2c -c mib2c.notify.conf FIGURE-IT-MIB::recordNotification
生成的代碼照例有些小問題,改掉就Ok了。
其實就一個函數:send_recordNotification_trap(),我們通過它來發送trap消息。
我對它做了點小改造:添加了一個string參數,這樣我們就可以發送不同的消息了。

3.將代碼添加到工程中,在需要發送trap的時候調用send_recordNotification_trap().

4.【重要提示!
修改配置文件:/usr/local/share/snmp/Record.conf
確保包含類似如下的內容:

trapsink localhost public

否則即使調用了send_recordNotification_trap()函數,也不會發送任何trap的。我之前測試很久,一直都沒有發送成功,添加這一行之后才Ok的。

SNMP的FAQ文檔中對此有說明:
“ If this file contains 'trapsink', then the agent will send an SNMPv1 trap. If this file contains 'trap2sink', then the agent will send an SNMPv2c trap. And if this file contains both, then the agent will send *two* copies of this trap.”

5.接收trap消息:
(1)修改/usr/local/share/snmp/snmptrapd.conf為如下內容:

1 authcommunity execute,log,net public #設置所有用戶的訪問權限:可 執行,記錄,傳遞
2 #traphandle default log_it#接收到trap的處理動作,可以不設置


(2)#sudo snmptrapd -d -f -Lo
如果有類似如下輸出,就說名發送trap消息成功了:

1 2012-03-29 16:52:54 192.168.110.68(via UDP: [127.0.0.1]:50370->[127.0.0.1]:162) TRAP, SNMP v1, community public
2 FIGURE-IT-MIB::record Enterprise Specific Trap (2) Uptime: 0:00:00.17
3 FIGURE-IT-MIB::recordTrapsEntry.0 = STRING: "[2012-03-29 16:52:51] NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNsnmp service is up and running."

同時通過tcpdump也可以看到發送的trap消息:
#sudo tcpdump -i lo udp

6.網上有人報告bug說,發送trap時使用的send_v2trap()函數存在內存泄漏。待研究。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM