在 net-snmp 原始碼目錄 agent/mibgroup/ 下建立自定義模組目錄:
agent/mibgroup/
├── MY/ # 自建模組目錄
│ ├── my_module.c # 實作檔
│ ├── my_module.h # 標頭檔
│ └── Makefile.in # 可選:自定義編譯規則
└── MY.h # 統一註冊標頭檔(關鍵)
agent/mibgroup/MY.h#ifndef MY_H
#define MY_H
// 向 net-snmp 註冊子模組
config_require(MY/my_module) // 對應 MY/my_module.c
#endif
agent/mibgroup/MY/my_module.c
#include
#include
#include "my_module.h"
// 定義 MIB 節點 OID: .1.3.6.1.4.1.8072.9999 (企業私有 OID 範例)
static oid my_oid[] = { 1, 3, 6, 1, 4, 1, 8072, 9999 };
// 處理函數
int handle_my_module(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
{
switch (reqinfo->mode) {
case MODE_GET:
snmp_set_var_typed_value(requests->requestvb, ASN_OCTET_STR,
"Hello World from net-snmp!", 28);
break;
default:
return SNMP_ERR_GENERR;
}
return SNMP_ERR_NOERROR;
}
// 模組初始化
void init_my_module(void)
{
netsnmp_register_scalar(
netsnmp_create_handler_registration(
"myModule", // 模組名稱
handle_my_module, // 處理函數
my_oid, OID_LENGTH(my_oid),
HANDLER_CAN_RONLY // 僅支援 GET
)
);
}
agent/mibgroup/MY/my_module.h#ifndef MY_MODULE_H
#define MY_MODULE_H
void init_my_module(void);
#endif
cd /path/to/net-snmp-source
./configure --with-mib-modules="MY" [其他原有選項...]
關鍵參數:--with-mib-modules="MY" 告訴建置系統編譯 MY 目錄下的模組。
make
sudo make install
# 檢查 snmpd.conf 是否載入
grep -r "my_module" /usr/local/share/snmp/mibs/
# 測試查詢
snmpget -v2c -c public localhost 1.3.6.1.4.1.8072.9999
# 應回傳: SNMPv2-SMI::enterprises.8072.9999 = STRING: "Hello World from net-snmp!"
| 錯誤現象 | 原因 | 解決方案 |
|---|---|---|
| configure 階段找不到模組 | 目錄結構不符或 MY.h 遺漏 | 確認 agent/mibgroup/MY.h 存在且 config_require 語法正確 |
| 編譯錯誤:未定義的參考 | init_my_module 未正確宣告/定義 | 檢查 .h/.c 函數簽名一致,且 .c 包含正確標頭檔 |
| snmpget 回傳 noSuchObject | OID 衝突或模組未註冊 | 確認 OID 唯一,檢查 snmpd.log 確認模組載入訊息 |
| 權限被拒絕 | snmpd.conf 社群字串/ACL 設定 | 修改 rocommunity 或 view 定義 |
建立 MY-MIB.txt 放入 /usr/local/share/snmp/mibs/,即可使用名稱查詢:
MY-MIB DEFINITIONS ::= BEGIN
IMPORTS
enterprises FROM SNMPv2-SMI;
myModule OBJECT-TYPE
SYNTAX DisplayString
MAX-ACCESS read-only
STATUS current
DESCRIPTION "Custom net-snmp module example"
::= { enterprises 8072 9999 }
END
snmpget -v2c -c public -M +/usr/local/share/snmp/mibs -m +MY-MIB localhost myModule
net-snmp 添加自定義 C 模組的核心步驟:建立模組目錄 → 撰寫實作與註冊標頭 → configure 指定模組 → 重新編譯安裝。關鍵在於 config_require() 機制與 --with-mib-modules 參數的正確使用。