net-snmp的嵌入式agent开发

常用命令:

ps -ax|grep snmpd
export MIBS=ALL;
snmptranslate -Tp -IR Test-MIB::Test
snmpget -v 2c -c public localhost sysUpTime.0

env MIBS="+/usr/local/net-snmp-5.8/share/snmp/mibs/Test-MIB.txt" mib2c -c mib2c.scalar.conf Test
env MIBS="+/usr/local/net-snmp-5.8/share/snmp/mibs/ZZZVPXTIMING-MIB.txt" mib2c -c mib2c.iterate.conf VPXTIMING

mipsel-linux-gcc -o Test Test.c -I /usr/local/net-snmp-mips/include -L/usr/local/net-snmp-mips/lib -lnetsnmp -lnetsnmpagent -lnetsnmphelpers  -lnetsnmpmibs -lpthread

/mnt/mtd/snmpd -Lf /mnt/mtd/snmpd.log -c /mnt/mtd/snmpd.conf -M /mnt/mtd/mibs
snmpget -v2c -c public 192.168.123.221 1.3.6.1.4.1.16535.1.1.0
snmpget -v2c -c public 192.168.123.221 1.3.6.1.4.1.16535.2.1.0
snmpgetnest -v2c -c public 192.168.123.221 1.3.6.1.4.1.16535.2
snmpwalk -v2c -c public 192.168.123.221 1.3.6.1.4.1.16535


一、安装嵌入式net-snmp

官网下载解压net-snmp-5.8,而后至解压目录(已创建好安装目录:/usr/local/net-snmp-mips)
1、配置

./configure -with-cc mipsel-linux-gcc -with-ar=mipsel-linux-ar -prefix=/usr/local/net-snmp-mips -build=i686-linux -host=mipsel-linux -with-endianness=little -disable-applications -disable-manuals -disable-debugging -disable-snmptrapd-subagent -disable-ipv6 -disable--scripts -enable-mini-agent -with-mib-modules="notification" -with-mib-modules="agentx" -disable-ucd-snmp-compatibility -disable-embedded-per -disable-perl-cc-checks -disable-without-perl-modules
参数(顺序不能更改):
 -with-cc mipsel-linux-gcc        指明编译时使用的编译器
 -with-ar=mipsel-linux-ar         指明编译库的工具
 -prefix=/usr/local/net-snmp-mips 指定交叉编译后的net-snmp代理软件的安装路径
 -build=i686-linux                指明编译源码的主机
 -host=mipsel-linux               指明运行该程序的机器平台,即运行代理的平台
 -with-endianness=little          指明采用小端模式
 -disable-applications            指明不编译SNMP的应用程序
 -disable-manuals                 指明取消编译帮助信息
 -disable-debugging               关闭调试信息
 -disable-snmptrapd-subagent      指明不支持snmptrapd子代理
 -disable-ipv6                    指明不支持ipv6
 -disable--scripts                指明不安装脚本
 -enable-mini-agent               指明安装最简单的代理
 -with-mib-modules="notification" 指明加载notification模块,用于发送trap
 -with-mib-modules="agentx"       指明加载agentx模块,此模块支持主代理和子代理,默认是子代理,可在snmpd.conf中配置为主代理
 -disable-ucd-snmp-compatibility  指明不安装UCD-SNMP的头文件和库
 -disable-embedded-per            指明不支持嵌入式perl
 -disable-perl-cc-checks          在支持嵌入式perl的情况下,不对编译perl的C编译器进行兼容性检查
 -disable-without-perl-modules    指明不支持perl模块

2、编译

make

3、安装

make install

4、裁减
进入安装目录net-snmp-mips/sbin下:

mipsel-linux-strip snmpd

进入安装目录net-snmp-mips/lib下:

mipsel-linux-strip libnetsnmp.so.35.0.0
mipsel-linux-strip libnetsnmpmibs.so.35.0.0
mipsel-linux-strip libnetsnmpagent.so.35.0.0
mipsel-linux-strip libnetsnmphelpers.so.35.0.0

5、编写snmpd.conf
snmpd.conf的基础配置
net-snmp安装配置手册

createUser liuming MDS 12345678 DES 87654321
rwuser liuming autb
com2sec local default public          #用户名local,密码public
com2sec mynetwork default private
group MyRWGroup  v1 local            #定义组名MyRWGroup,安全级别v1,加入组成员local
group  MyRWGroup v2c local
group  MyRWGroup usm local
group  MyROGroup v1 mynetwork
group  MyROGroup v2c mynetwork
group  MyROGroup usm mynetwork
view all included .180              #定义视图名为all,包含,范围
access  MyROGroup "" any  noauth  exact  all  none none   #定义用户组在视图all中的操作权限读(access group context sec.model sec.level prefix read  write notif )
access   MyRWGroup "" any   noauth  exact  all  all none
master on
trapsink 192.168.0.19:162
trap2sink 192.168.0.19:162
intormsink 192.168.0.19:162
trapsess 192.168.0.19
agentAddress udp:161
rocommunity public
 
 
com2sec notConfigUser  default       public
#group notConfigGroup v1           notConfigUser
group notConfigGroup v2c           notConfigUser
#group notConfigGroup usm           notConfigUser
view all included .1 
access notConfigGroup ""      any       noauth    exact  all none none
access notConfigGroup "interface2"      usm       priv    exact  if2 if2 if2
 
 
 
#建立用户
#noAuthNoPriv
#关键字	用户名
#createUser admin1
 
#authNoPriv
#关键字	用户名	认证方式	密码(长度不小于8个字符)
#createUser admin2 MD5 11111111
#createUser admin3 SHA 11111111
 
#authPriv
#关键字	用户名	认证方式	密码(长度不小于8个字符)	加密方式 口令(长度不小于8个字符)
#createUser admin4 MD5 11111111 DES 22222222
#createUser admin5 MD5 11111111 AES 22222222
#createUser admin6 SHA 11111111 DES 22222222
#createUser admin7 SHA 11111111 AES 22222222
 
#定义权限
#权限	用户名
#rouser admin1 noauth
#rouser admin2
#rouser admin3
#rouser admin4
#rwuser admin5
#rwuser admin6
#rwuser admin7
 
##################trap auto ####################
#trapsink 127.0.0.1:162 public
trap2sink 10.20.70.51:162 public
#informsink 127.0.0.1:162
 
#trapsess -v 3 -u 用户名  -e  引擎ID       -a 验证方式 -A 验证码  -l  鉴权方式   目的IP
#-e 引擎ID 可省略  若省略则系统自己生成一个引擎ID
#trapsess -v 3 -u admin1 -e 0x010203040506 -l noAuthNoPriv 10.20.84.189
#trapsess -v 3 -u admin2 -e 0x010203040506 -a MD5 -A 111111111 -l authNoPriv 10.20.84.189
#trapsess -v 3 -u admin3 -e 0x010203040506 -a SHA -A 111111111 -l authNoPriv 10.20.84.189
#trapsess -v 3 -u admin4 -e 0x010203040506 -a MD5 -A 111111111 -x DES -X 22222222 -l authNoPriv 10.20.84.189
#trapsess -v 3 -u admin5 -e 0x010203040506 -a MD5 -A 111111111 -x AES -X 22222222 -l authNoPriv 10.20.84.189
#trapsess -v 3 -u admin6 -e 0x010203040506 -a SHA -A 111111111 -x DES -X 22222222 -l authNoPriv 10.20.84.189
#trapsess -v 3 -u admin7 -e 0x010203040506 -a SHA -A 111111111 -x AES -X 22222222 -l authNoPriv 10.20.84.189

下面是作为主代理,来供子代理连接的snmp.conf文件

master agentx
rocommunity public
rwcommunity public

6、移植拷贝文件

命名Test-MIB.my,放在/usr/local/share/snmp/mibs目录下,因为这个目录是snmpd的默认目录,只要把MIB库放入该目录就可以自动加载MIB库,否则需要修改/etc/snmp/snmp.conf文件,添加mibs +/path/to/Test-MIB.my 并重启snmpd。
/usr/local/share/snmp/mibs
/etc/snmp/snmp.conf

(1)进入开发板/mnt/mtd目录

snmpd  (net-snmp-mips/sbin)
snmpd.conf  (自己创建的)

(2)在/mnt/mtd目录下创建mibs文件夹

(net-snmp-mips/share/snmp/mibs目录下)
SNMPv2-SMI.txt
SNMPv2-MIB.txt
SNMPv2-TC.txt
RFC1213-MIB.txt
IF-MIB.txt
IP-MIB.txt
TCP-MIB.txt
UDP-MIB.txt
SNMP-VIEW-BASED-ACM-MIB.txt
SNMP-USER-BASED-SM-MIB.txt
SNMP-COMMUNITY-MIB.txt
SNMP-FRAMEWORK-MIB.txt
SNMP-MPD-MIB.txt
SNMP-TARGET-MIB.txt
IANAifType-MIB.txt
INET-ADDRESS-MIB.txt


(3)在/mnt/mtd目录下创建lib文件夹

(net-snmp-mips/lib)
libnetsnmp.so.35.0.0
libnetsnmpmibs.so.35.0.0
libnetsnmpagent.so.35.0.0
libnetsnmphelpers.so.35.0.0

(4)创建符号链接(在/mnt/mtd目录下)

ln -s /mnt/mtd/lib/libnetsnmp.so.35.0.0 /lib/libnetsnmp.so.35
ln -s /mnt/mtd/lib/libnetsnmpmibs.so.35.0.0 /lib/libnetsnmpmibs.so.35
ln -s /mnt/mtd/lib/libnetsnmpagent.so.35.0.0 /lib/libnetsnmpagent.so.35
ln -s /mnt/mtd/lib/libnetsnmphelpers.so.35.0.0 /lib/libnetsnmphelpers.so.35

(5)拷贝必需库文件(在/usr/lib目录下)

tftp -g -r librt.so.1 192.168.123.220
tftp -g -r libnl-3.so.200 192.168.123.220
tftp -g -r libpthread.so.0 192.168.123.220
tftp -g -r libm.so.6 192.168.123.220

7、测试

vi snmpd.log 
./snmpd -Lf snmpd.log -c /mnt/mtd/snmpd.conf -M /mnt/mtd/mibs
netstat -lnp | grep snmpd
snmpget -v2c -c public 192.168.123.221 system.sysContact.0
snmpwalk -v2c -c public 192.168.123.221 1.3.6.1.2.1.1

通过FTP将snmpd.log传回PC查看,若snmpd.conf中配置为主代理(master on)和子代理(master agentx)分别为:

主代理:
Turning on agentX master support
NET-SNMP version 5.8.0
子代理:
NET-SNMP version 5.8.0
snmpd -c /etc/snmpd/snmpd.conf -f -Le -d -M /etc/snmpd/mibs
启动参数(snmpd命令的有用选项):
-c FILE 指定文件为配置文件
-C 不读取默认的配置文件
-d dump接收和发送SNMP数据包
-D TOKEN 对于给定的TOKEN(标志)打开调试信息 ( -Dmib_init)
-I [-]INITLIST 对于要初始化的MIB列表显示
-M DIRLIST 指定MIB库的路径
-V 显示详细信息
-Le 把错误信息输出到日志中
-Lf FILE 把错误信息输出到指定文件中
-Lo 把程序输出打印到屏幕
-m MIBLIST use MIBLIST instead of the default MIB list
-f    防止snmpd fork成后台进程do not fork from the shell

二、编写MIB文件

编写自己的MIB文件:ZZZVPXTIMING-MIB.txt
具体语法见:关于SNMP的MIB文件的语法简述

--this is my vpxtiming mib,annotation
VPXTIMING-MIB DEFINITIONS::=BEGIN

IMPORTS
	OBJECT-GROUP,MODULE-COMPLIANCE,NOTIFICATION-GROUP
		FROM SNMPv2-CONF
	enterprises
		FROM RFC1155-SMI
	Integer32,Unsigned32,OBJECT-TYPE,MODULE-IDENTITY,NOTIFICATION-TYPE
		FROM SNMPv2-SMI
	DisplayString
		FROM RFC1213-MIB
	RowStatus, TEXTUAL-CONVENTION
		FROM SNMPv2-TC;
--; is the end of IMPORTS

VPXTIMING MODULE-IDENTITY
	LAST-UPDATED "201912011930Z"    --Y M D H M S
	 ORGANIZATION
		 "HeBeiJingHe"
	CONTACT-INFO
		"phone:18781113079"
	DESCRIPTION
		"vpxtiming MIB"
	::= {enterprises 19980 }

-- the vpxtiming group

locationTable OBJECT IDENTIFIER::={VPXTIMING 1}
timeTable OBJECT IDENTIFIER::={VPXTIMING 2}

--first nod 
locationTable OBJECT-TYPE
	SYNTAX SEQUENCE OF LocationEntry
	MAX-ACCESS not-accessible
	STATUS current
	DESCRIPTION "This is the first table of vpxtimg"
	::={VPXTIMING 1}
locationEntry OBJECT-TYPE
	SYNTAX LocationEntry
	MAX-ACCESS not-accessible
	STATUS current
	DESCRIPTION "This is the entry of locationTable"
	INDEX {locationIndex}
	::={locationTable 1}
	LocationEntry::=SEQUENCE
	{
		locationIndex Integer32,
		longitude Integer32,
		latitude    Integer32,
		speed      Integer32,
		yaw         Integer32
	}
locationIndex OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={locationEntry 1}
longitude OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={locationEntry 2}
latitude OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={locationEntry 3}
speed OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={locationEntry 4}
yaw OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={locationEntry 5}


--second nod 
timeTable OBJECT-TYPE
	SYNTAX SEQUENCE OF TimeEntry
	MAX-ACCESS not-accessible
	STATUS current
	DESCRIPTION "This is the second table of vpxtimg"
	::={VPXTIMING 2}
timeEntry OBJECT-TYPE
	SYNTAX TimeEntry
	MAX-ACCESS not-accessible
	STATUS current
	DESCRIPTION "This is the entry of timeTable"
	INDEX {timeIndex}
	::={timeTable 1}
	LocationEntry::=SEQUENCE
	{
		timeIndex Integer32,
		year        Integer32,
		month    Integer32,
		day         Integer32,
		hour        Integer32
	}
timeIndex OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={timeEntry 1}
year OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={timeEntry 2}
month OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={timeEntry 3}
day OBJECT-TYPE
	SYNTAX Integer32
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={timeEntry 4}
hour OBJECT-TYPE
	SYNTAX DisplayString (SIZE (0..100))
	MAX-ACCESS read-only
	STATUS current
	DESCRIPTION " "
	::={timeEntry 5}



END

检测MIB:

snmptranslate -Tp -IR Test-MIB::Test

关于table
net-snmp代理开发之表格开发入门
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、mib2c

将自己编写的MIB文件(ZZZVPXTIMING-MIB.txt)放入自己net-snmp安装目录下的/net-snmp-5.8/shares/snmp/mibs目录下,在开发目录下执行:

env MIBS="+/usr/local/net-snmp-5.8/share/snmp/mibs/ZZZVPXTIMING-MIB.txt" mib2c -c mib2c.iterate.conf VPXTIMING

mib2c的命令格式为:

mib2c [-h] -c CONFIGFILE [-I PATH] [-f OUTNAME] [-i] [q] [-S VAR=VAL] MIBNODE
-c 指定模板配置文件,必选项
-I 指定模板配置文件的搜索路径
-f 指定输出c语言代码的文件名(默认为MIBNODE.c/.h) 

设置环境变量,用对应配置文件生成代码。注意要用root权限。

export MIBS=ALL;
mib2c –c configure mibnode

configure选择:

表格用mib2c.iterate_access.conf或mib2c.iterate.conf
节点用mib2c.scalar.conf
Trap用mib2c.notify.conf

四、修改c代码实现get和set功能

参考:net-snmp子代理(SubAgent)编写
net-snmp的MIBs扩展_添加set
a) 节点方式函数
handle_XXX(netsnmp_mib_handler *handler,
netsnmp_handler_registration *reginfo,
netsnmp_agent_request_info *reqinfo,
netsnmp_request_info *requests)
MODE_GET用于get操作;
MODE_SET_COMMIT用于写操作。从requests->requestvb->val.integer/string获取节点数据。

b) table方式函数说明(mib2c.iterate_access.conf):
initialize_table_xxxTable(void)
模块初始化

xxxTable_handler
表格处理函数句柄

xxxTable_createEntry
传入表格参数,新建一个结构,将各参数依次赋给结构内各项。最后将结构添加在xxxTable_head的前面作为首节点。

xxxTable_removeEntry
此函数可借用mib2c.iterate.conf文件生成的函数。
entry的意思表示是表格的入口,是在mib文件中设置的(index项)。可查看netsnmp_table_helper_add_indexes函数的第二个参数注释。

xxxTable_get_first_data_point
手动创建链表,每个节点包含一行table内容,头结点赋给xxxTable_head。
将xxxTable_head赋给 *my_loop_context。

xxxTable_get_next_data_point
需要填写snmp_set_var_value(idx, (u_char *)xxx, sizeof(xxx))的后两个参数,xxx为index项。

xxxTable_create_data_context(netsnmp_variable_list * index_data, int column)
创建一个结构模板,entry项由index_data传入,如下例:
entry->IPLineID = *(index_data->val.integer); 其他的项随便填。如有RowStatus项,则RowStatus初始化为0。
将创建的结构体添加到xxxTable_head的头结点前面。
本函数在在xxxTable_handler函数中调用,默认生成的模板里第二个参数为空,编译会出错,填入1。

xxxTable_commit_row(void **my_data_context, int new_or_del)
具体的添加修改删除行的操作在这个函数里进行。例:
struct IPLineTable_entry *entry = (IPL_t *)*my_data_context;
switch (entry->RowStatus)
根据entry->RowStatus的不同类型区分不同的操作。

Get_xxx (void *data_context, size_t *ret_len)
获取节点数据内容

Set_xxx (void *data_context, long *val, size_t val_len)
设置节点内容

c) trap函数
发送trap有两种方式,一种是脚本中用snmptrap发送,一种是在程序内用函数发送。发送函数:send_xxxTrap_trap()。
需要填写两个snmp_varlist_add_variable函数。
snmp_varlist_add_variable(&var_list, snmptrap_oid, OID_LENGTH(snmptrap_oid),
ASN_OBJECT_ID, (u_char *)xxxTrap_oid, sizeof(xxxTrap_oid));
snmp_varlist_add_variable(&var_list, yyy_oid, OID_LENGTH(yyy_oid),
ASN_OCTET_STR, string, strlen(string));
xxxTrap_oid是trap节点号,yyy_oid是关联节点号,string即为要发送的字符串。

1、报错点修改
(1)第一个参数后面要加...
/* create a new row in the (unsorted) table */
struct gnssTable_entry *
gnssTable_createEntry(
long dataindex,…
) {
struct gnssTable_entry *entry;
(2)error: duplicate member ‘locationIndex’
注释掉一个

五、编译运行

1、静态编译
重新使用configure,并指定需要编译的代理模块:

./configure --with-mib-modules="nstAgentModuleObject"

把Test.c和Test.h复制到/net-snmp-5.7.3/agent/mibgroups,这里是说net-snmp源码里。
编译./configure --prefix=/usr/local/snmp --with-mib-modules=Test,make && make install。
静态加载成功

2、动态编译

$ cc 'net-snmp-config --cflags' -fPIC -shared -g -O0 -o nstAgentPluginObject.so nstAgentPluginObject.c 'net-snmp-config --libs'

对于简单的标量开发而言,以上方法没有问题,对于表格的情况,mib2c生成了多个文件,需要写自己的Makefile来编译。

#!/bin/sh
LIB=$(patsubst %.c,%.o,$(wildcard *.c))
DLL=lampController.so
CFLAGS+= -fno-strict-aliasing -g -O2 -Ulinux -Dlinux=linux -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/lib64/perl5/CORE -I. -I/usr/local/include
DLLLDFLAGS='net-snmp-config --libs'
all:$(DLL)
$(DLL):%.so:$(LIB)
        gcc $(DLLLDFLAGS) -shared -rdynamic -g  $^ -o $@
$(LIB):%.o:%.c
        gcc -c $(CFLAGS) -g -dH -fPIC -Wall $^ -o $@
clean:
        rm -rf *.o

运行和测试:
将生成的VPXTIMING.so文件拷入目录下,
启动snmp进程,通过-D可以打开调试:

snmpd -f -Lo -Ddlmod,lampController

此时既可以通过snmpwalk取得对应的数据了:

snmpget -v2c -c public localhost WILLSERVICE-ROADLAMP-GATEWAY-MIB::controllerCount.0

————————————————————————————————————————————————————————————
对比,还没整理:

CC=gcc
FLAGS=-I. `net-snmp-config --cflags` -g
DLFLAGS=-shared -fPIC -g

Test.so: Test.c
    $(CC) $(CFLAGS) $(DLFLAGS) -c -o Test.o Test.c
    $(CC) $(CFLAGS) $(DLFLAGS) -o Test.so Test.o

.PHONY : clean
clean :
    rm -f *.so *.o

编译生成.so库。
修改snmpd.conf配置文件,在文件末尾加入dlmod Test ${Test.so所在绝对路径}/Test.so
启动snmpd,
/usr/local/snmpd -f -L -DTest,dlmod -c /usr/local/snmp/etc/snmpd.conf
动态加载完成


添加扩展采用动态库方式
生成动态库:

gcc -g -I/root/net-snmp-5.2.2/include/ -c -o example.o example.c
gcc -g -fPIC -shared -o example.so example.o

装载动态库到程序节点
需要配置文件:/etc/snmp/snmpd.conf 中添加

dlmod   example    /root/snmpdll/ example.so

然后重新启动snmpd程序。

3、子代理

生成Test子代理程序:

net-snmp-config --compile-subagent Test Test.c

启动snmpd主代理,再执行Test子代理程序:

/usr/local/snmpd -c /usr/local/snmp/etc/snmpd.conf
./Test

再调用snmpget来测试结果:

 snmpget -v2c -c public localhost 1.3.6.1.4.1.16535.1.1.0

子代理扩展完成。

4、shell 方式
(待补充)

六、直接加入项目

0、这个是在mib2c上直接加main()后的编译命令

gcc  -std=c99 -fno-strict-aliasing -g -O2 -Ulinux -Dlinux=linux  -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -Wdeclaration-after-statement -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm  -I/usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/CORE   -I. -I/usr/local/net-snmp-5.8/include -o Test Test.c  -L/usr/local/net-snmp-5.8/lib -lnetsnmpmibs -lnetsnmpagent -lnetsnmp -lnetsnmpmibs    -lnetsnmpagent  -Wl,-E -Wl,-rpath,/usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi/CORE -lnetsnmp 
mipsel-linux-gcc -o Test Test.c -I /usr/local/net-snmp-mips/include -L/usr/local/net-snmp-mips/lib -lnetsnmp -lnetsnmpagent -lnetsnmphelpers  -lnetsnmpmibs -lpthread

1、将c代码加入到工程中
将生成的recordStatusTable.c和recordStatusTable.h文件加入到工程中,修改Makefile,添加net-snmp头文件和库依赖。net-snmp的头文件在源码目录下的include目录下,即/include;库文件一般在/usr/lib下。

#ls /usr/lib |grep libnetsn
libnetsnmpagent.so.15
libnetsnmpagent.so.15.1.2
libnetsnmphelpers.so.15
libnetsnmphelpers.so.15.1.2
libnetsnmpmibs.so.15
libnetsnmpmibs.so.15.1.2
libnetsnmp.so.15
libnetsnmp.so.15.1.2
libnetsnmptrapd.so.15
libnetsnmptrapd.so.15.1.2

在Makefile中添加“-lnetsnmp -lnetsnmpagent -lnetsnmphelpers -lnetsnmptrapd -lnetsnmpmibs”即可。

2、在项目中开启一个线程,启动snmp服务

 void CSnmpThread::run()
  {
      LOG(LOG_TYPE_NOTICE, "[Thread] CSnmpThread Start.");
 
      int agentx_subagent=0; /* change this if you want to be a SNMP master agent */
      int background = 0; /* change this if you want to run in the background */
      int syslog = 0; /* change this if you want to use syslog */
  
      //snmp_set_do_debugging(1);
 
     /* print log errors to syslog or stderr */
     if (syslog)
     {
         snmp_enable_calllog();
     }
     else
     {
         snmp_enable_stderrlog();
     }
 
     /* we're an agentx subagent? */
     if (agentx_subagent)
     {
         /* make us a agentx client. */
         netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 1);
     }
 
     /* run in background, if requested */
     if (background && netsnmp_daemonize(1, !syslog))
     {
         LOG(LOG_TYPE_NOTICE, "netsnmp_daemonize() failed. [Thread] CSnmpThread exit!");
         return;
     }
 
     /* Initialize tcpip, if necessary */
     SOCK_STARTUP;
 
     /* Initialize the agent library */
     init_agent("Record");
 
     /* Initialize our mib code here */
     init_recordStatusTable(); // 加载节点信息
 
     /* initialize vacm/usm access control  */
 //    if (!agentx_subagent)
 //    {
 //        void  init_vacm_vars();
 //        void  init_usmUser();
 //    }
 
     /* Example-demon will be used to read example-demon.conf files. */
     init_snmp("Record");// 配置文件名---->/usr/local/share/snmp/Record.conf
 
     /* If we're going to be a snmp master agent, initial the ports */
     if (!agentx_subagent)
     {
         init_master_agent();  /* open the port to listen on (defaults to udp:161) */
     }
 
     /* In case we recevie a request to stop (kill -TERM or kill -INT) */
     keep_running = 1;
     //signal(SIGTERM, stop_server);
 //signal(SIGINT, stop_server);
 
     LOG(LOG_TYPE_INFO,"snmp service is up and running");
 
     /* your main loop here... */
     while(keep_running)
     {
         /* if you use select(), see snmp_select_info() in snmp_api(3) */
         /*     --- OR ---  */
         agent_check_and_process(1); /* 0 == don't block */
     }
 
     /* at shutdown time */
     snmp_shutdown("Record");
     SOCK_CLEANUP;
     return;
 }

3、编写配置文件Record.conf,放到vi /usr/local/share/snmp/下(和主代理snmpd.conf同目录,开发板上是:/mnt/mtd)。
(1)snmpd.conf内容:

###########################################################################
#
# snmpd.conf
#
#   - created by the snmpconf configuration program
#
########################################################myself
rocommunity public
rwcommunity private
 
#--      securityname    source     community 
com2sec  roUser         default       public
com2sec  rwUser         default      private

#--  groupname    securityModel securityname
group  roGroup      v1              roUser
group  roGroup      v2c             roUser
group  rwGroup      v1              rwUser
group  rwGroup      v2c              rwUser

#view viewname type   oid
#view   all  included .1
view    all  included .1 

#access groupname  context model   level     prefx   read   write  notify
access   roGroup    ""      any    noauth    exact    all   none    none
access   rwGroup    ""      any    noauth    exact    all    all    none

master agentx
agentXTimeout 5
agentXRetries 2

(2)Record.conf内容(我的是Test.conf):

#agentXSocket tcp:localhost:705
agentXTimeout 10
agentXRetries 1
agentXPingInterval 20

4、测试snmp
(1)编译程序。sudo后以root权限运行,否则会报错:

“Error opening specified endpoint "161"”

(2)snmpwalk -v1 -c public localhost recordStatusTable
如果看到返回信息,就说明成功了。若不成功,用snmpgetnext命令试试会得到下一个正确的节点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值