├── ch10 ├── __init__.py ├── query.py └── nmsapp.py ├── ch12 ├── app.c ├── snmpipc.c ├── snmpipc.h ├── public │ ├── public.c │ ├── public.h │ └── snmpipc.h ├── alarms │ ├── sysAlarms.c │ ├── notificationObjs.c │ ├── sysAlarms.h │ ├── notificationObjs.h │ └── mib2c.txt ├── parameter │ ├── parameter.c │ ├── mib2c.txt │ └── parameter.h ├── realtimedata │ ├── realTimeData.c │ ├── realTimeData.h │ ├── realTimeData_access.c │ ├── realTimeData_enums.h │ ├── realTimeData_checkfns_local.c │ ├── realTimeData_columns.h │ ├── realTimeData_checkfns_local.h │ ├── realTimeData_checkfns.c │ ├── realTimeData_checkfns.h │ ├── realTimeData_access.h │ └── mib2c.txt └── doc │ ├── mib2c.old-api-refactor-c.conf │ ├── mib2c.old-api-refactor.conf │ ├── mib2c-1.txt │ ├── configure.txt │ └── mib2c.old-api-refactor-h.conf ├── ch8 ├── list.c ├── list.h ├── tools.c ├── tools.h ├── defines.h ├── nmsapp.c ├── nmsapp.h ├── nmsapp │ ├── mibs │ │ ├── general │ │ │ └── monitor.oids │ │ ├── 192.168.43.132 │ │ │ └── monitor.oids │ │ └── 192.168.43.146 │ │ │ └── monitor.oids │ └── nmshosts.conf ├── ch8-8-4.jpg ├── Makefile ├── instrument.c文件说明 ├── instrument.c └── snmpdemoapp.c ├── ch9 ├── app.c ├── public │ ├── public.c │ ├── public.h │ └── snmpipc.h ├── alarms │ ├── sysAlarms.c │ ├── notificationObjs.c │ ├── sysAlarms.h │ ├── notificationObjs.h │ └── mib2c.txt ├── parameter │ ├── parameter.c │ ├── mib2c.txt │ └── parameter.h ├── realtimedata │ ├── realTimeData.c │ ├── realTimeData.h │ ├── realTimeData_access.c │ ├── realTimeData_enums.h │ ├── realTimeData_checkfns_local.c │ ├── realTimeData_columns.h │ ├── realTimeData_checkfns_local.h │ ├── realTimeData_checkfns.c │ ├── realTimeData_checkfns.h │ ├── realTimeData_access.h │ └── mib2c.txt ├── configure.txt ├── snmpipc.h ├── BOOK-APP-MIB.mib ├── BOOK-EXAMPLE-MIB.my └── snmpipc.c ├── 《深入理解Net-SNMP》第15章 测试与调试-张春强.pdf ├── ch7 ├── cacti.conf ├── php.conf ├── snmpd.conf └── httpd.conf ├── README ├── ch11 └── perl_mysql │ ├── makemysqlmib.pl │ └── mysql_agent.pl └── ch4 ├── BOOK-EXAMPLE-MIB(original).my └── BOOK-EXAMPLE-MIB.my /ch10/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #means package -------------------------------------------------------------------------------- /ch12/app.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/app.c -------------------------------------------------------------------------------- /ch8/list.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/list.c -------------------------------------------------------------------------------- /ch8/list.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/list.h -------------------------------------------------------------------------------- /ch8/tools.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/tools.c -------------------------------------------------------------------------------- /ch8/tools.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/tools.h -------------------------------------------------------------------------------- /ch9/app.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/app.c -------------------------------------------------------------------------------- /ch8/defines.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/defines.h -------------------------------------------------------------------------------- /ch8/nmsapp.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/nmsapp.c -------------------------------------------------------------------------------- /ch8/nmsapp.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/nmsapp.h -------------------------------------------------------------------------------- /ch8/nmsapp/mibs/general/monitor.oids: -------------------------------------------------------------------------------- 1 | SNMPv2-MIB::system.sysContact.0 2 | .1.3.6.1.2.1.1.6.0 3 | -------------------------------------------------------------------------------- /ch12/snmpipc.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/snmpipc.c -------------------------------------------------------------------------------- /ch12/snmpipc.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/snmpipc.h -------------------------------------------------------------------------------- /ch8/ch8-8-4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch8/ch8-8-4.jpg -------------------------------------------------------------------------------- /ch12/public/public.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/public/public.c -------------------------------------------------------------------------------- /ch12/public/public.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/public/public.h -------------------------------------------------------------------------------- /ch12/public/snmpipc.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/public/snmpipc.h -------------------------------------------------------------------------------- /ch9/public/public.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/public/public.c -------------------------------------------------------------------------------- /ch9/public/public.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/public/public.h -------------------------------------------------------------------------------- /ch9/public/snmpipc.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/public/snmpipc.h -------------------------------------------------------------------------------- /ch12/alarms/sysAlarms.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/alarms/sysAlarms.c -------------------------------------------------------------------------------- /ch9/alarms/sysAlarms.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/alarms/sysAlarms.c -------------------------------------------------------------------------------- /ch12/parameter/parameter.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/parameter/parameter.c -------------------------------------------------------------------------------- /ch9/parameter/parameter.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/parameter/parameter.c -------------------------------------------------------------------------------- /ch12/alarms/notificationObjs.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/alarms/notificationObjs.c -------------------------------------------------------------------------------- /ch9/alarms/notificationObjs.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/alarms/notificationObjs.c -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/realtimedata/realTimeData.c -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/realtimedata/realTimeData.h -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/realtimedata/realTimeData.c -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/realtimedata/realTimeData.h -------------------------------------------------------------------------------- /《深入理解Net-SNMP》第15章 测试与调试-张春强.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/《深入理解Net-SNMP》第15章 测试与调试-张春强.pdf -------------------------------------------------------------------------------- /ch12/doc/mib2c.old-api-refactor-c.conf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/doc/mib2c.old-api-refactor-c.conf -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_access.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch9/realtimedata/realTimeData_access.c -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_access.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chansonZ/Understanding-the-Net-SNMP/HEAD/ch12/realtimedata/realTimeData_access.c -------------------------------------------------------------------------------- /ch8/nmsapp/mibs/192.168.43.132/monitor.oids: -------------------------------------------------------------------------------- 1 | SNMPv2-MIB::system.sysUpTime.0 2 | SNMPv2-MIB::system.sysName.0 3 | .1.3.6.1.4.1.2020.15.1.2.1 4 | .1.3.6.1.2.1.1.5.0 5 | .1.3.6.1.2.1.2.1.0 6 | 7 | -------------------------------------------------------------------------------- /ch12/doc/mib2c.old-api-refactor.conf: -------------------------------------------------------------------------------- 1 | ## mib2c -c mib2c.old-api-refactor.conf BOOK-APP-MIB::parameter 2 | @run mib2c.old-api-refactor-h.conf@ 3 | 4 | @run mib2c.old-api-refactor-c.conf@ 5 | 6 | @quit@ -------------------------------------------------------------------------------- /ch8/nmsapp/mibs/192.168.43.146/monitor.oids: -------------------------------------------------------------------------------- 1 | .1.3.6.1.2.1.2.2 2 | SNMPv2-MIB::system.sysUpTime.0 3 | SNMPv2-MIB::system.sysName.0 4 | .1.3.6.1.2.1.1.5.0 5 | .1.3.6.1.2.1.2.1.0 6 | .1.3.6.1.2.1.2.2.1.2.1 7 | -------------------------------------------------------------------------------- /ch8/Makefile: -------------------------------------------------------------------------------- 1 | 2 | BUILDLIBS=`net-snmp-config --libs` 3 | CFLAGS=-g -O0 4 | OBJS=nmsapp.o list.o tools.o 5 | 6 | all:$(OBJS) 7 | gcc -o nmsapp $(CFLAGS) $(BUILDLIBS) $(OBJS) 8 | 9 | clean: 10 | rm -f *.o nmsapp 11 | -------------------------------------------------------------------------------- /ch12/doc/mib2c-1.txt: -------------------------------------------------------------------------------- 1 | 2 | @open -@ 3 | @foreach $t table@ 4 | mibnode type oidlength OID 5 | ----------------------------------------------------- 6 | @foreach $c column@ 7 | $c $c.type $c.oidlength $c.objectID 8 | @end@ 9 | @end@ -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_enums.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_ENUMS_H 6 | #define REALTIMEDATA_ENUMS_H 7 | 8 | 9 | #endif /* REALTIMEDATA_ENUMS_H */ 10 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_enums.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_ENUMS_H 6 | #define REALTIMEDATA_ENUMS_H 7 | 8 | 9 | #endif /* REALTIMEDATA_ENUMS_H */ 10 | -------------------------------------------------------------------------------- /ch12/parameter/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | mib2c -c mib2c.old-api.conf BOOK-APP-MIB::parameter 3 | 4 | [/mnt/hgfs/shareLinux/snmp/ch9/src/parameter]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::parameter 5 | writing to parameter.h 6 | writing to parameter.c 7 | running indent on parameter.c 8 | running indent on parameter.h -------------------------------------------------------------------------------- /ch9/parameter/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | mib2c -c mib2c.old-api.conf BOOK-APP-MIB::parameter 3 | 4 | [/mnt/hgfs/shareLinux/snmp/ch9/src/parameter]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::parameter 5 | writing to parameter.h 6 | writing to parameter.c 7 | running indent on parameter.c 8 | running indent on parameter.h -------------------------------------------------------------------------------- /ch8/nmsapp/nmshosts.conf: -------------------------------------------------------------------------------- 1 | [192.168.43.146] 2 | user=MD5_DES_User2 3 | securityLevel=3 4 | auth_passphrase=P@ssw0rd 5 | priv_passphrase=P@ssw0rd_DES 6 | frequency=5 7 | 8 | [192.168.43.132:161] 9 | user=MD5_DES_User2 10 | securityLevel=3 11 | auth_passphrase=P@ssw0rd 12 | priv_passphrase=P@ssw0rd_DES 13 | frequency=5 14 | -------------------------------------------------------------------------------- /ch7/cacti.conf: -------------------------------------------------------------------------------- 1 | Alias /cacti /var/www/html/cacti 2 | 3 | 4 | AllowOverride None 5 | Order Deny,Allow 6 | Allow from all 7 | #Deny from all 8 | #Allow from 127.0.0.1 9 | #Allow from ::1 10 | Options Indexes Includes FollowSymLinks 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_checkfns_local.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | 6 | /* 7 | * standard headers 8 | */ 9 | #include 10 | #include 11 | #include "realTimeData_checkfns.h" 12 | #include "realTimeData_enums.h" 13 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_checkfns_local.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | 6 | /* 7 | * standard headers 8 | */ 9 | #include 10 | #include 11 | #include "realTimeData_checkfns.h" 12 | #include "realTimeData_enums.h" 13 | -------------------------------------------------------------------------------- /ch8/instrument.c文件说明: -------------------------------------------------------------------------------- 1 | instrument.c: 2 | 该文件是用于 C/C++中用于自动生成函数关系调用图的 3 | 请参考 http://www.ibm.com/developerworks/cn/linux/l-graphvis/ 4 | 第8章 中的函数关系调用图是由它们做出来的,这张图就是:图8-4 程序运行流程图 5 | 如何编译: 将 -finstrument-functions 加入到 CFLAGS 标识中 6 | 7 | 主要过程: 8 | 编译: CFLAGS=-g -O0 -finstrument-functions 9 | 运行程序:./nmsapp 10 | 运行pvtrace: ./pvtrace nmsapp 上述产生 graph.dot文件 11 | 输出图形:dot -Tjpg graph.dot -o test4.jpg 12 | -------------------------------------------------------------------------------- /ch12/alarms/sysAlarms.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef SYSALARMS_H 6 | #define SYSALARMS_H 7 | #include "../public/public.h" 8 | 9 | /* 10 | * function declarations 11 | */ 12 | //int send_sysAlarmNotify_trap(void); 13 | void register_read_alarmdata(); 14 | 15 | 16 | #endif /* SYSALARMS_H */ 17 | -------------------------------------------------------------------------------- /ch9/alarms/sysAlarms.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef SYSALARMS_H 6 | #define SYSALARMS_H 7 | #include "../public/public.h" 8 | 9 | /* 10 | * function declarations 11 | */ 12 | //int send_sysAlarmNotify_trap(void); 13 | void register_read_alarmdata(); 14 | 15 | 16 | #endif /* SYSALARMS_H */ 17 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_columns.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_COLUMNS_H 6 | #define REALTIMEDATA_COLUMNS_H 7 | 8 | /* 9 | * column number definitions for table realTimeDataTable 10 | */ 11 | #define COLUMN_REALTIMEDATAINDEX 1 12 | #define COLUMN_REALTIMEDATAX1 2 13 | #define COLUMN_REALTIMEDATAY2 3 14 | #endif /* REALTIMEDATA_COLUMNS_H */ 15 | -------------------------------------------------------------------------------- /ch12/alarms/notificationObjs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef NOTIFICATIONOBJS_H 6 | #define NOTIFICATIONOBJS_H 7 | config_require(book-app-mib/alarms/sysAlarms) 8 | #include "../public/public.h" 9 | 10 | /* 11 | * function declarations 12 | */ 13 | void init_notificationObjs(void); 14 | FindVarMethod var_notificationObjs; 15 | WriteMethod write_alarmCounter; 16 | 17 | #endif /* NOTIFICATIONOBJS_H */ 18 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_columns.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_COLUMNS_H 6 | #define REALTIMEDATA_COLUMNS_H 7 | 8 | /* 9 | * column number definitions for table realTimeDataTable 10 | */ 11 | #define COLUMN_REALTIMEDATAINDEX 1 12 | #define COLUMN_REALTIMEDATAX1 2 13 | #define COLUMN_REALTIMEDATAY2 3 14 | #define COLUMN_REALTIMEDATA_MAX (COLUMN_REALTIMEDATAY2-1) 15 | #endif /* REALTIMEDATA_COLUMNS_H */ 16 | -------------------------------------------------------------------------------- /ch9/alarms/notificationObjs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef NOTIFICATIONOBJS_H 6 | #define NOTIFICATIONOBJS_H 7 | config_require(book-app-mib/alarms/sysAlarms) 8 | #include "../public/public.h" 9 | 10 | /* 11 | * function declarations 12 | */ 13 | void init_notificationObjs(void); 14 | FindVarMethod var_notificationObjs; 15 | WriteMethod write_alarmCounter; 16 | 17 | #endif /* NOTIFICATIONOBJS_H */ 18 | -------------------------------------------------------------------------------- /ch9/parameter/parameter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef PARAMETER_H 6 | #define PARAMETER_H 7 | #include "../public/public.h" 8 | 9 | /* 10 | * function declarations 11 | */ 12 | void init_parameter(void); 13 | FindVarMethod var_parameter; 14 | FindVarMethod var_parameterTable; 15 | WriteMethod write_parameterA; 16 | WriteMethod write_parameterB; 17 | WriteMethod write_parameterC1; 18 | 19 | #endif /* PARAMETER_H */ 20 | -------------------------------------------------------------------------------- /ch12/alarms/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | mib2c -c mib2c.notify.conf BOOK-APP-MIB::sysAlarms 4 | 5 | [/mnt/hgfs/shareLinux/snmp/ch9/src/alarms]# mib2c -c mib2c.notify.conf BOOK-APP-MIB::sysAlarms 6 | writing to sysAlarms.h 7 | writing to sysAlarms.c 8 | running indent on sysAlarms.h 9 | running indent on sysAlarms.c 10 | 11 | 12 | [/mnt/hgfs/shareLinux/snmp/ch9/src/alarms]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::notificationObjs 13 | writing to notificationObjs.h 14 | writing to notificationObjs.c 15 | running indent on notificationObjs.c 16 | running indent on notificationObjs.h -------------------------------------------------------------------------------- /ch9/alarms/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | mib2c -c mib2c.notify.conf BOOK-APP-MIB::sysAlarms 4 | 5 | [/mnt/hgfs/shareLinux/snmp/ch9/src/alarms]# mib2c -c mib2c.notify.conf BOOK-APP-MIB::sysAlarms 6 | writing to sysAlarms.h 7 | writing to sysAlarms.c 8 | running indent on sysAlarms.h 9 | running indent on sysAlarms.c 10 | 11 | 12 | [/mnt/hgfs/shareLinux/snmp/ch9/src/alarms]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::notificationObjs 13 | writing to notificationObjs.h 14 | writing to notificationObjs.c 15 | running indent on notificationObjs.c 16 | running indent on notificationObjs.h -------------------------------------------------------------------------------- /ch9/configure.txt: -------------------------------------------------------------------------------- 1 | ./configure --prefix="/usr/local/mynetsnmp/" --with-openssl=internal \ 2 | -with-default-snmp-version="2" --with-sys-contact="xtdwxk@gmail.com" \ 3 | --with-sys-location="shenzhenXL" \ 4 | --with-logfile=/usr/local/mynetsnmp/var/log/snmpd.log \ 5 | --with-persistent-directory=/usr/local/mynetsnmp/var/net-snmp \ 6 | --with-python-modules \ 7 | --with-cflags="-g -O0" \ 8 | --with-libs="-lsnmpipc" \ 9 | --with-mib-modules="book-app-mib/public/public,book-app-mib/parameter/parameter,book-app-mib/realtimedata/realTimeData,book-app-mib/alarms/notificationObjs" 10 | -------------------------------------------------------------------------------- /ch12/doc/configure.txt: -------------------------------------------------------------------------------- 1 | ./configure --prefix="/usr/local/mynetsnmp/" --with-openssl=internal \ 2 | -with-default-snmp-version="2" --with-sys-contact="xtdwxk@gmail.com" \ 3 | --with-sys-location="shenzhenXL" \ 4 | --with-logfile=/usr/local/mynetsnmp/var/log/snmpd.log \ 5 | --with-persistent-directory=/usr/local/mynetsnmp/var/net-snmp \ 6 | --with-python-modules \ 7 | --with-cflags="-g -O0" \ 8 | --with-libs="-lsnmpipc" \ 9 | --with-mib-modules="book-app-mib/public/public,book-app-mib/parameter/parameter,book-app-mib/realtimedata/realTimeData,book-app-mib/alarms/notificationObjs" 10 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_checkfns_local.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * : $ 4 | * 5 | */ 6 | #ifndef REALTIMEDATA_CHECKFNS_H 7 | #define REALTIMEDATA_CHECKFNS_H 8 | 9 | /* 10 | * these functions are designed to check incoming values for 11 | * columns in the realTimeDataTable table for legality with respect to 12 | * datatype and value according to local conventions. You should modify 13 | * them as appropriate. They will be called from parent check_value 14 | * functions that are auto-generated using mib2c and the parent functions 15 | * should NOT be modified. 16 | */ 17 | 18 | 19 | #endif /* REALTIMEDATA_CHECKFNS_H */ 20 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_checkfns_local.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * : $ 4 | * 5 | */ 6 | #ifndef REALTIMEDATA_CHECKFNS_H 7 | #define REALTIMEDATA_CHECKFNS_H 8 | 9 | /* 10 | * these functions are designed to check incoming values for 11 | * columns in the realTimeDataTable table for legality with respect to 12 | * datatype and value according to local conventions. You should modify 13 | * them as appropriate. They will be called from parent check_value 14 | * functions that are auto-generated using mib2c and the parent functions 15 | * should NOT be modified. 16 | */ 17 | 18 | 19 | #endif /* REALTIMEDATA_CHECKFNS_H */ 20 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_checkfns.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | 6 | /******************************************************************** 7 | * NOTE NOTE NOTE 8 | * This file is auto-generated and SHOULD NOT BE EDITED by hand. 9 | * Modify the realTimeData_checkfns_local.[ch] files insead so that you 10 | * can regenerate this one as mib2c improvements are made. 11 | ********************************************************************/ 12 | 13 | /* 14 | * standard headers 15 | */ 16 | #include 17 | #include 18 | #include "realTimeData_checkfns.h" 19 | #include "realTimeData_checkfns_local.h" 20 | #include "realTimeData_enums.h" 21 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_checkfns.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | 6 | /******************************************************************** 7 | * NOTE NOTE NOTE 8 | * This file is auto-generated and SHOULD NOT BE EDITED by hand. 9 | * Modify the realTimeData_checkfns_local.[ch] files insead so that you 10 | * can regenerate this one as mib2c improvements are made. 11 | ********************************************************************/ 12 | 13 | /* 14 | * standard headers 15 | */ 16 | #include 17 | #include 18 | #include "realTimeData_checkfns.h" 19 | #include "realTimeData_checkfns_local.h" 20 | #include "realTimeData_enums.h" 21 | -------------------------------------------------------------------------------- /ch7/php.conf: -------------------------------------------------------------------------------- 1 | # 2 | # PHP is an HTML-embedded scripting language which attempts to make it 3 | # easy for developers to write dynamically generated webpages. 4 | # 5 | 6 | LoadModule php5_module modules/libphp5.so 7 | 8 | 9 | LoadModule php5_module modules/libphp5-zts.so 10 | 11 | 12 | # 13 | # Cause the PHP interpreter to handle files with a .php extension. 14 | # 15 | AddHandler php5-script .php 16 | AddType text/html .php 17 | 18 | # 19 | # Add index.php to the list of files that will be served as directory 20 | # indexes. 21 | # 22 | DirectoryIndex index.php 23 | 24 | # 25 | # Uncomment the following line to allow PHP to pretty-print .phps 26 | # files as PHP source code: 27 | # 28 | #AddType application/x-httpd-php-source .phps 29 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_checkfns.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * : mib2c.iterate.conf,v 5.6 2003/02/20 00:52:07 hardaker Exp $ 4 | */ 5 | 6 | /*********************************************************************** 7 | * This file is auto-generated and SHOULD NOT BE EDITED by hand. 8 | * Modify the realTimeData_checkfns_local.[ch] files insead. 9 | * (so that you can regenerate this one as mib2c improvements are made) 10 | ***********************************************************************/ 11 | #ifndef REALTIMEDATA_CHECKFNS_H 12 | #define REALTIMEDATA_CHECKFNS_H 13 | 14 | /** make sure we load the functions that you can modify */ 15 | config_require(book-app-mib/realtimedata/realTimeData_checkfns_local) 16 | 17 | /* 18 | * these functions are designed to check incoming values for 19 | * columns in the realTimeDataTable table for legality with respect to 20 | * datatype and value. 21 | */ 22 | #endif /* REALTIMEDATA_CHECKFNS_H */ 23 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_checkfns.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * : mib2c.iterate.conf,v 5.6 2003/02/20 00:52:07 hardaker Exp $ 4 | */ 5 | 6 | /*********************************************************************** 7 | * This file is auto-generated and SHOULD NOT BE EDITED by hand. 8 | * Modify the realTimeData_checkfns_local.[ch] files insead. 9 | * (so that you can regenerate this one as mib2c improvements are made) 10 | ***********************************************************************/ 11 | #ifndef REALTIMEDATA_CHECKFNS_H 12 | #define REALTIMEDATA_CHECKFNS_H 13 | 14 | /** make sure we load the functions that you can modify */ 15 | config_require(book-app-mib/realtimedata/realTimeData_checkfns_local) 16 | 17 | /* 18 | * these functions are designed to check incoming values for 19 | * columns in the realTimeDataTable table for legality with respect to 20 | * datatype and value. 21 | */ 22 | #endif /* REALTIMEDATA_CHECKFNS_H */ 23 | -------------------------------------------------------------------------------- /ch12/parameter/parameter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * mib2c.old-api-refactor.conf Sat Oct 11 17:57:43 2014 4 | * zhangchunqiang 2014-10 $ 5 | */ 6 | #ifndef PARAMETER_H 7 | #define PARAMETER_H 8 | 9 | /* !!! please fill the module path completely that we have developed !!!*/ 10 | #include "../public/public.h" 11 | 12 | /*--define scalar magic number,easy enum*/ 13 | typedef enum 14 | { 15 | PARAMETERA = 1, 16 | PARAMETERB, 17 | }E_scalar_parameter_magic; 18 | 19 | /*--define table magic number*/ 20 | typedef enum 21 | { 22 | PARAMETERINDEX = 1, 23 | PARAMETERC1, 24 | }E_table_parameter_magic; 25 | 26 | 27 | /* function declarations */ 28 | void init_parameter(void); 29 | FindVarMethod var_parameter; 30 | FindVarMethod var_parameterTable; 31 | 32 | /*one scalar write is ok*/ 33 | WriteMethod write_parameter_scalar; 34 | 35 | 36 | /* --table write */ 37 | WriteMethod write_parameterTable; 38 | 39 | /*if you have other special code,you can write here */ 40 | 41 | #endif /* PARAMETER_H */ 42 | -------------------------------------------------------------------------------- /ch12/realtimedata/realTimeData_access.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_ACCESS_H 6 | #define REALTIMEDATA_ACCESS_H 7 | 8 | #include "../public/public.h" 9 | #include "realTimeData_columns.h" 10 | 11 | 12 | /** User-defined data access functions for data in table realTimeDataTable */ 13 | /** row level accessors */ 14 | Netsnmp_First_Data_Point realTimeDataTable_get_first_data_point; 15 | Netsnmp_Next_Data_Point realTimeDataTable_get_next_data_point; 16 | int realTimeDataTable_commit_row(void **my_data_context, 17 | int new_or_del); 18 | void *realTimeDataTable_create_data_context(netsnmp_variable_list 19 | * index_data, 20 | int column); 21 | 22 | /** column accessors */ 23 | long *get_realTimeDataIndex(void *data_context, size_t *ret_len); 24 | long *get_realTimeDataX1(void *data_context, size_t *ret_len); 25 | long *get_realTimeDataY2(void *data_context, size_t *ret_len); 26 | 27 | void init_table_realtime_data(void); 28 | 29 | 30 | #endif /* REALTIMEDATA_ACCESS_H */ 31 | -------------------------------------------------------------------------------- /ch9/realtimedata/realTimeData_access.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Note: this file originally auto-generated by mib2c using 3 | * $ 4 | */ 5 | #ifndef REALTIMEDATA_ACCESS_H 6 | #define REALTIMEDATA_ACCESS_H 7 | 8 | #include "../public/public.h" 9 | #include "realTimeData_columns.h" 10 | 11 | 12 | /** User-defined data access functions for data in table realTimeDataTable */ 13 | /** row level accessors */ 14 | Netsnmp_First_Data_Point realTimeDataTable_get_first_data_point; 15 | Netsnmp_Next_Data_Point realTimeDataTable_get_next_data_point; 16 | int realTimeDataTable_commit_row(void **my_data_context, 17 | int new_or_del); 18 | void *realTimeDataTable_create_data_context(netsnmp_variable_list 19 | * index_data, 20 | int column); 21 | 22 | /** column accessors */ 23 | long *get_realTimeDataIndex(void *data_context, size_t *ret_len); 24 | long *get_realTimeDataX1(void *data_context, size_t *ret_len); 25 | long *get_realTimeDataY2(void *data_context, size_t *ret_len); 26 | 27 | void init_table_realtime_data(void); 28 | 29 | 30 | #endif /* REALTIMEDATA_ACCESS_H */ 31 | -------------------------------------------------------------------------------- /ch8/instrument.c: -------------------------------------------------------------------------------- 1 | /******************************************************************** 2 | * File: instrument.c 3 | * 4 | * Instrumentation source -- link this with your application, and 5 | * then execute to build trace data file (trace.txt). 6 | * 7 | * Author: M. Tim Jones 8 | * 9 | */ 10 | 11 | #include 12 | #include 13 | 14 | /* Function prototypes with attributes */ 15 | void main_constructor( void ) 16 | __attribute__ ((no_instrument_function, constructor)); 17 | 18 | void main_destructor( void ) 19 | __attribute__ ((no_instrument_function, destructor)); 20 | 21 | void __cyg_profile_func_enter( void *, void * ) 22 | __attribute__ ((no_instrument_function)); 23 | 24 | void __cyg_profile_func_exit( void *, void * ) 25 | __attribute__ ((no_instrument_function)); 26 | 27 | 28 | static FILE *fp; 29 | 30 | 31 | void main_constructor( void ) 32 | { 33 | fp = fopen( "trace.txt", "w" ); 34 | if (fp == NULL) exit(-1); 35 | } 36 | 37 | 38 | void main_deconstructor( void ) 39 | { 40 | fclose( fp ); 41 | } 42 | 43 | 44 | void __cyg_profile_func_enter( void *this, void *callsite ) 45 | { 46 | fprintf(fp, "E%p\n", (int *)this); 47 | } 48 | 49 | 50 | void __cyg_profile_func_exit( void *this, void *callsite ) 51 | { 52 | fprintf(fp, "X%p\n", (int *)this); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | README file for source code of book《深入理解Net-SNMP》 2 | 3 | DISCLAIMER 4 | 5 | The Authors assume no responsibility for damage or loss of system 6 | performance as a direct or indirect result of the use of this 7 | software. This software is provided "as is" without express or 8 | implied warranty. 9 | 10 | TABLE OF CONTENTS 11 | 12 | Disclaimer 13 | Table Of Contents 14 | Introduction 15 | Availability 16 | Installation 17 | Copying And Copyrights 18 | Frequently Asked Questions 19 | Mailing Lists 20 | Thanks 21 | 22 | 23 | INTRODUCTION 24 | 25 | 《深入理解Net-SNMP》的源码,基于Net-SNMP 5.7.2开发。 26 | 27 | 28 | AVAILABILITY 29 | 30 | Download: 31 | - https://github.com/chansonZ/Understanding-the-Net-SNMP 32 | - http://www.net-snmp.org/download/ (Net-SNMP) 33 | 34 | 35 | INSTALLATION 36 | 37 | 请参考书中对应章节。 38 | 39 | COPYING AND COPYRIGHTS 40 | 41 | See the COPYING file distributed with this package. 42 | 43 | FREQUENTLY ASKED QUESTIONS 44 | 45 | QQ:203127943 46 | 47 | 48 | MAILING LISTS 49 | 50 | Mail: xtdwxk@gmail.com 51 | 52 | 53 | THANKS 54 | 55 | Wes Hardaker 56 | 钟志勇,徐鑫鑫,白良浩,郑坤 57 | 58 | BUY LINKS 59 | http://product.dangdang.com/23762017.html 60 | https://item.jd.com/11755316.html (京东自营已无货,可选其他书店或电子书) 61 | https://www.amazon.cn/dp/B0144HF92S 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /ch9/realtimedata/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | [/mnt/hgfs/shareLinux/snmp/ch9/src/realtimedata]# mib2c -c mib2c.iterate_access.conf BOOK-APP-MIB::realTimeData 5 | writing to realTimeData.h 6 | writing to realTimeData_columns.h 7 | writing to realTimeData_enums.h 8 | writing to realTimeData.c 9 | writing to realTimeData_checkfns_local.h 10 | writing to realTimeData_checkfns_local.c 11 | writing to realTimeData_checkfns.h 12 | writing to realTimeData_checkfns.c 13 | writing to realTimeData_access.h 14 | writing to realTimeData_access.c 15 | writing to - 16 | 17 | ********************************************************************** 18 | NOTE: The only files you MUST modify should be the following: 19 | realTimeData_access.c 20 | realTimeData_access.h 21 | realTimeData_checkfns_local.h 22 | realTimeData_checkfns_local.c 23 | ********************************************************************** 24 | 25 | running indent on realTimeData_access.c 26 | running indent on realTimeData_checkfns_local.c 27 | running indent on realTimeData_access.h 28 | running indent on realTimeData_enums.h 29 | running indent on realTimeData.c 30 | running indent on realTimeData.h 31 | running indent on realTimeData_columns.h 32 | running indent on realTimeData_checkfns.c 33 | running indent on realTimeData_checkfns_local.h 34 | running indent on realTimeData_checkfns.h 35 | [/mnt/hgfs/shareLinux/snmp/ch9/src/realtimedata]# 36 | 37 | 38 | [/mnt/hgfs/shareLinux/snmp/ch9/src]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::realTimeData 39 | writing to realTimeData.h 40 | writing to realTimeData.c 41 | running indent on realTimeData.c 42 | running indent on realTimeData.h 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /ch12/realtimedata/mib2c.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | [/mnt/hgfs/shareLinux/snmp/ch9/src/realtimedata]# mib2c -c mib2c.iterate_access.conf BOOK-APP-MIB::realTimeData 5 | writing to realTimeData.h 6 | writing to realTimeData_columns.h 7 | writing to realTimeData_enums.h 8 | writing to realTimeData.c 9 | writing to realTimeData_checkfns_local.h 10 | writing to realTimeData_checkfns_local.c 11 | writing to realTimeData_checkfns.h 12 | writing to realTimeData_checkfns.c 13 | writing to realTimeData_access.h 14 | writing to realTimeData_access.c 15 | writing to - 16 | 17 | ********************************************************************** 18 | NOTE: The only files you MUST modify should be the following: 19 | realTimeData_access.c 20 | realTimeData_access.h 21 | realTimeData_checkfns_local.h 22 | realTimeData_checkfns_local.c 23 | ********************************************************************** 24 | 25 | running indent on realTimeData_access.c 26 | running indent on realTimeData_checkfns_local.c 27 | running indent on realTimeData_access.h 28 | running indent on realTimeData_enums.h 29 | running indent on realTimeData.c 30 | running indent on realTimeData.h 31 | running indent on realTimeData_columns.h 32 | running indent on realTimeData_checkfns.c 33 | running indent on realTimeData_checkfns_local.h 34 | running indent on realTimeData_checkfns.h 35 | [/mnt/hgfs/shareLinux/snmp/ch9/src/realtimedata]# 36 | 37 | 38 | [/mnt/hgfs/shareLinux/snmp/ch9/src]# mib2c -c mib2c.old-api.conf BOOK-APP-MIB::realTimeData 39 | writing to realTimeData.h 40 | writing to realTimeData.c 41 | running indent on realTimeData.c 42 | running indent on realTimeData.h 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /ch10/query.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import netsnmp 4 | import sys,os 5 | 6 | 7 | class HostResult(): 8 | """This creates a host record""" 9 | def __init__(self, 10 | hostname = None, 11 | result = None): 12 | 13 | self.hostname = hostname 14 | self.result = result 15 | 16 | class PysnmpClass(object):#Version=3,host='localhost', 17 | '''A Class For python SNMP''' 18 | def __init__(self,host='localhost',*oids,**para): 19 | 20 | #oid可以传入原始的OID 21 | #也可以传入已经格式化绑定的OID 22 | self.oids = oids 23 | self.Version = 3 24 | self.DestHost = host 25 | self.SecLevel=para['securityLevel'] 26 | self.SecName=para['user'] 27 | self.PrivPass=para['priv_passphrase'] 28 | self.AuthPass=para['auth_passphrase'] 29 | self.hostrecd=HostResult(self.DestHost) 30 | 31 | def query(self): 32 | '''Creates SNMP query session''' 33 | result = None 34 | try: 35 | sess = netsnmp.Session(Version = self.Version, 36 | DestHost=self.DestHost, 37 | SecLevel=self.SecLevel, 38 | SecName=self.SecName, 39 | PrivPass=self.PrivPass, 40 | AuthPass=self.AuthPass, 41 | ) 42 | 43 | vars = netsnmp.VarList( *self.oids ) 44 | result = sess.get(vars) 45 | except Exception, err: 46 | print 'except:',err 47 | #返回元组(type, value, traceback)的异常信息 48 | #print sys.exc_info() 49 | result = None 50 | finally: 51 | self.hostrecd.result = result 52 | return self.hostrecd # 返回一个HostResult类。直接打印类即可显示结果 53 | -------------------------------------------------------------------------------- /ch12/doc/mib2c.old-api-refactor-h.conf: -------------------------------------------------------------------------------- 1 | ###################################################################### 2 | ## Do the .h file 3 | ###################################################################### 4 | @eval $date=scalar localtime; @ 5 | @open ${name}.h@ 6 | /* 7 | * Note: this file originally auto-generated by mib2c using 8 | * mib2c.old-api-refactor.conf $date 9 | * zhangchunqiang 2014-10 $ 10 | */ 11 | #ifndef $name.uc_H 12 | #define $name.uc_H 13 | 14 | /* !!! please fill the module path completely that we have developed !!!*/ 15 | #include "../public/public.h" 16 | 17 | /*--define scalar magic number,easy enum*/ 18 | typedef enum 19 | { 20 | @eval $first = 0@ 21 | @foreach $i scalar@ 22 | @if $first eq 0@ 23 | $i.uc = 1, 24 | @eval $first = 1@ 25 | @else@ 26 | $i.uc, 27 | @eval $endid = $i.uc@ 28 | @end@ 29 | @end@ 30 | }E_scalar_${name}_magic; 31 | 32 | /*--define table magic number*/ 33 | @eval $first = 0@ 34 | typedef enum 35 | { 36 | @foreach $j table@ 37 | @foreach $c column@ 38 | @if $first eq 0@ 39 | $c.uc = 1, 40 | @eval $first = 1@ 41 | @else@ 42 | $c.uc, 43 | @end@ 44 | @end@ 45 | @end@ 46 | }E_table_${name}_magic; 47 | 48 | 49 | /* function declarations */ 50 | void init_$name(void); 51 | FindVarMethod var_$name; 52 | @foreach $i table@ 53 | FindVarMethod var_${i}; 54 | @end@ 55 | 56 | /*one scalar write is ok*/ 57 | @eval $x = 0@ 58 | @foreach $i scalar@ 59 | @if $i.settable@ 60 | @eval $x = 1@ 61 | @end@ 62 | @end@ 63 | @if $x eq 1@ 64 | WriteMethod write_${name}_scalar; 65 | @end@ 66 | 67 | 68 | /* --table write */ 69 | @foreach $i table@ 70 | @eval $x = table_is_writable($i)@ 71 | @if $x eq 1@ 72 | WriteMethod write_${i}; 73 | @end@ 74 | @end@ 75 | 76 | /*if you have other special code,you can write here */ 77 | 78 | #endif /* $name.uc_H */ 79 | -------------------------------------------------------------------------------- /ch11/perl_mysql/makemysqlmib.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -w 2 | 3 | # Now SNMP tools are enterprisey. 4 | # They won't even give you the current uptime without a MIB. 5 | # So for "SHOW GLOBAL STATUS" we need a MIB file as well. 6 | # That is why I like perl so much. It gets things done. 7 | # In this case, it is making me a MIB file out of a MySQL connection. 8 | 9 | ############## 10 | # ./makemysqlmib.pl > mysqlmib 11 | #[/mnt/hgfs/centosShare/perl/monitor_mysql]# smistrip mysqlmib 12 | # MYSQL-MIB: 4133 lines. 13 | # smilint -m /usr/local/share/snmp/mibs/NET-SNMP-MIB.txt ./MYSQL-MIB 14 | 15 | # XX:echo "mibs +MYSQL-MIB" > snmp.conf 16 | # export MIBS=ALL 17 | # snmptranslate -On -Tp -IR mysqlMIB| less 18 | ############## 19 | use strict; 20 | use DBI; 21 | 22 | # 配置链接数据库的信息 23 | my $dsn = "DBI:mysql:host=127.0.0.1;port=3306"; 24 | my $user = "user"; 25 | my $pass = "password"; 26 | # 声明数组变量 27 | my @global_status_name = (); 28 | my @mibName = (); 29 | 30 | # 使用DBI链接数据库并执行“show global status”命令 31 | my $dbh = DBI->connect($dsn, $user, $pass) or die("connect");#数据库句柄 32 | my $cmd = "SHOW /*!50002 GLOBAL */ STATUS";# 执行的指令 33 | 34 | 35 | my $result = $dbh->selectall_arrayref($cmd); 36 | my $i = 1; 37 | 38 | foreach my $row (@$result) { 39 | # $status{$row->[0]} = $row->[1]; 40 | my $name = $row->[0] ; 41 | $global_status_name[$i] = $name; 42 | $name =~ s/_(.)/\U$1\E/g; 43 | # $output{ "my$mib_name" } = $row->[1]; 44 | $mibName[$i] = "my$name"; 45 | $i++; 46 | } 47 | 48 | # 断开链接 49 | $dbh->disconnect(); 50 | 51 | # 生成MIB文件头部信息 52 | print qq(MYSQL-MIB DEFINITIONS ::= BEGIN 53 | IMPORTS 54 | MODULE-IDENTITY, OBJECT-TYPE 55 | FROM SNMPv2-SMI 56 | DisplayString 57 | FROM SNMPv2-TC 58 | 59 | MODULE-COMPLIANCE, OBJECT-GROUP 60 | FROM SNMPv2-CONF 61 | 62 | netSnmpPlaypen 63 | FROM NET-SNMP-MIB; 64 | 65 | 66 | mysqlMIB MODULE-IDENTITY 67 | LAST-UPDATED "201411270000Z" 68 | ORGANIZATION "book example" 69 | CONTACT-INFO 70 | "xtdwxk\@gmail.com" 71 | DESCRIPTION 72 | "mysql status" 73 | REVISION "201411270000Z" 74 | DESCRIPTION 75 | "mysql status MIB" 76 | ::= { netSnmpPlaypen 2 } 77 | 78 | mysqlStatus OBJECT IDENTIFIER ::= { mysqlMIB 1 } 79 | ); 80 | 81 | # 所有的信息都定义为只读、字符型类型 82 | for (my $i=1; $i < @global_status_name; $i++) { 83 | printf qq(%s OBJECT-TYPE 84 | SYNTAX DisplayString 85 | MAX-ACCESS read-only 86 | STATUS current 87 | DESCRIPTION "SHOW /*!50002 GLOBAL */ STATUS LIKE '%s'" 88 | ::= { mysqlStatus %d } 89 | 90 | ), 91 | $mibName[$i], 92 | $global_status_name[$i], 93 | $i; 94 | } 95 | 96 | # 加入一致性声明 97 | print qq( 98 | mySQLMIBConformance OBJECT IDENTIFIER ::= { mysqlMIB 2 } 99 | mySQLMIBCompliances OBJECT IDENTIFIER ::= { mySQLMIBConformance 1 } 100 | mySQLMIBGroups OBJECT IDENTIFIER ::= { mySQLMIBConformance 2 } 101 | 102 | mySQLMIBCompliance MODULE-COMPLIANCE 103 | STATUS current 104 | DESCRIPTION 105 | "The compliance statement for SNMPv2 entities which implement MYSQL." 106 | MODULE -- this module 107 | MANDATORY-GROUPS { mySQLGroup } 108 | ::= { mySQLMIBCompliances 1 } 109 | ); 110 | 111 | # 加入组-part1 112 | print qq( 113 | mySQLGroup OBJECT-GROUP 114 | OBJECTS { 115 | ); 116 | 117 | # 加入组-part2 118 | my $j=1; 119 | for ($j=1; $j < @mibName-1; $j++) { 120 | printf qq(%s, 121 | ), $mibName[$j]; 122 | } 123 | printf qq(%s),$mibName[$j]; 124 | 125 | # 加入组-part3 126 | print qq( 127 | } 128 | STATUS current 129 | DESCRIPTION 130 | "The group of objects providing for management of MYSQL entities." 131 | ::= { mySQLMIBGroups 1 } 132 | ); 133 | 134 | # 加入MIB 结束符END 135 | print qq( 136 | END 137 | ); 138 | -------------------------------------------------------------------------------- /ch8/snmpdemoapp.c: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 从最简单的同步应用学Net-SNMP通讯流程: 4 | 在这里我们的通信主机仅仅一台,获取的对象只有两个 5 | make: gcc snmpdemoapp.c `net-snmp-config --libs` -o snmpdemoapp 6 | gcc snmpdemoapp.c -L/usr/local/lib -lnetsnmp -lrt -lm -o snmpdemoapp 7 | 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | int main (int argc, char **argv) 15 | { 16 | /* 17 | 结构体 netsnmp_session 中记录了SNMP会话信息; 18 | 第一个变量需要填充准备会话的信息, 19 | 第二个为一指针用于记录库返回的会话信息; 20 | */ 21 | netsnmp_session session, *ss; 22 | 23 | // 该结构体中记录了远程主机所有的信息 24 | netsnmp_pdu *pdu; 25 | 26 | // 该结构体中记录了远程主机返回的PDU信息 27 | netsnmp_pdu *response; 28 | 29 | // 记录OID节点位置信息 30 | oid anOID[MAX_OID_LEN]; 31 | size_t anOID_len; 32 | 33 | // 变量绑定列表(为list数据结构),也就是需要操作的数据 34 | netsnmp_variable_list *vars; 35 | int status; 36 | int count=1; 37 | 38 | /* 39 | 初始SNMP库: 40 | 初始化互斥量、MIB 解析、传输层、 41 | 调试信息的初始化、解析配置文件的初始化(netsnmp_ds_register_config)、各句柄的初始化 42 | 定时器的初始化、读取配置文件 43 | */ 44 | init_snmp("snmpdemoapp"); 45 | 46 | /* 47 | session 的初始化:包括初始化目的地,SNMP协议版本、认证机制、 48 | 初始化会话结构体(为默认值),不涉及任何的MIB文件处理 49 | */ 50 | snmp_sess_init( &session ); 51 | // 设置会话结构体:目标地址;可以为其他有效的网络地址 52 | session.peername = strdup("localhost"); 53 | 54 | // 使用SNMPv1版本 55 | session.version = SNMP_VERSION_1; 56 | 57 | // 设置共同体 58 | session.community = "public"; 59 | session.community_len = strlen(session.community); 60 | 61 | /* 62 | 开启和绑定底层的传输层(TCP/UDP),建立会话,返回会话句柄. 63 | 每个回话都对应一个socket 64 | */ 65 | ss = snmp_open(&session); 66 | 67 | if (!ss) { 68 | snmp_sess_perror("snmpdemoapp", &session); // 记录错误信息到日志中, 69 | exit(1); 70 | } 71 | /* 回话创建完成后,接下来是创建指定类型(命令类型)的PDU, 72 | 作为本次回话的实例执行指定操作的准备, 73 | 这就包括绑定准备通信的OID。 74 | */ 75 | pdu = snmp_pdu_create(SNMP_MSG_GET); 76 | anOID_len = MAX_OID_LEN; // 该宏值为128,正如RFC建议所述“节点下子OID数量不超过128个”。 77 | 78 | /* 79 | 此处 read_objid / snmp_parse_oid的作用是检查OID的正确性, 80 | 并赋予anOID正确的值,也就是最终请求的OID 81 | */ 82 | //read_objid("system.sysDescr.0", anOID, &anOID_len); 83 | 84 | //if (!snmp_parse_oid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len)) { 85 | if (!snmp_parse_oid("system.sysDescr.0", anOID, &anOID_len)) { 86 | snmp_perror(".1.3.6.1.2.1.1.1.0"); 87 | exit(1); 88 | } 89 | 90 | /* 91 | 按照协议PDU格式的要求,我们将该OID加入到PDU报文中, 92 | 同时赋予一个NULL值作为变量的绑定; 93 | 当然对于SET命令的PDU来说就是赋予待设置的值。 94 | */ 95 | snmp_add_null_var(pdu, anOID, anOID_len); 96 | 97 | //同步发送报文 98 | status = snmp_synch_response(ss, pdu, &response); 99 | 100 | /* 101 | 下面的代码是处理返回的PDU报文,我们需要根据返回的信息作出合理的后续处理: 102 | 报文的返回和执行状态都正确,读取返回的值 103 | */ 104 | if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) { 105 | //将读取到的返回值打印到标准输出(stdout)出来 106 | for(vars = response->variables; vars; vars = vars->next_variable) 107 | print_variable(vars->name, vars->name_length, vars); 108 | 109 | //处理(打印)接收到的信息: 110 | for(vars = response->variables; vars; vars = vars->next_variable) { 111 | if (vars->type == ASN_OCTET_STR) { 112 | char *sp = (char *)malloc(1 + vars->val_len); 113 | memcpy(sp, vars->val.string, vars->val_len); 114 | sp[vars->val_len] = '\0'; 115 | printf("value #%d is a string: %s\n", count++, sp); 116 | free(sp); 117 | } 118 | else 119 | printf("value #%d is NOT a string! Ack!\n", count++); 120 | } 121 | } else { 122 | 123 | // 如果返回值有错误:打印其错误信息 124 | if (status == STAT_SUCCESS) 125 | fprintf(stderr, "Error in packet\nReason: %s\n", 126 | snmp_errstring(response->errstat)); 127 | else if (status == STAT_TIMEOUT) 128 | fprintf(stderr, "Timeout: No response from %s.\n", 129 | session.peername); 130 | else 131 | snmp_sess_perror("snmpdemoapp", ss); //记录错误日志 132 | 133 | } 134 | 135 | //释放分配的空间;关闭会话,关闭socket,释放资源 136 | if (response) 137 | snmp_free_pdu(response); 138 | snmp_close(ss); 139 | return (0); 140 | } 141 | -------------------------------------------------------------------------------- /ch9/snmpipc.h: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | * Copyright (C) GPL 3 | * FileName: snmpipc.h 4 | * Author: 张春强 5 | * Date: 2014-08 6 | ***********************************************************/ 7 | 8 | #ifndef SNMPIPC_H 9 | #define SNMPIPC_H 10 | 11 | #ifdef __cplusplus 12 | extern "C" { 13 | #endif /*__cplusplus */ 14 | 15 | // 保证该目录已经存在 16 | #define APP_DIR "/usr/local/etc/app/shm/" 17 | #define SHM_CONF "shm.conf" 18 | #define SEM_CONF "sem.conf" 19 | 20 | #define SHM_KEY_ID 1 21 | #define SEM_KEY_ID 1 22 | 23 | #define SUCCESS 0 24 | #define FAILURE -1 25 | typedef int BOOLEAN; 26 | 27 | // 数据类型定义 28 | typedef enum 29 | { 30 | // 从 0 开始,与数组,信号量匹配 31 | SHM_PARADATA = 0, // 参数数据类型 32 | SHM_REALDATA, // 实时数据类型 33 | SHM_ALARM, // 告警数据类型 34 | SHM_CTRL, // 控制数据类型 35 | } SHM_TYPE; 36 | #define SHM_PARAMETER ( SHM_PARADATA ) 37 | 38 | 39 | typedef struct 40 | { 41 | int iSize; //真实结构体大小或通用结构体大小 42 | void *pShmAddr; 43 | } T_ShareMem; 44 | 45 | #define SHM_TYPE_NUM ( SHM_CTRL + 1 ) // 需要保存在共享内存中的数据类型数量 46 | 47 | // 信号量数量:每种数据种类一个信号量 48 | #define SEM_NUM SHM_TYPE_NUM 49 | 50 | #define TO_SHM ( 0 ) 51 | #define FROM_SHM ( 1 ) 52 | 53 | #define SLAVE ( 0 ) 54 | #define MASTER ( 1 ) 55 | 56 | #define MAX_CHAR_LEN (32) // 系统中字符串参数最大长度,4的倍数 57 | typedef union 58 | { 59 | int iValue; // 统一的整形数据 60 | char acValue[MAX_CHAR_LEN]; // 统一的字符串类型数据 61 | } U_Value; 62 | 63 | 64 | typedef struct 65 | { 66 | int iNo; 67 | int iOffset; 68 | int iLen; 69 | } T_MapTable; 70 | 71 | /*参数数据: 模拟整形,字符型,简单表一多行单列 */ 72 | #define C_ROW_NUM (3) 73 | typedef struct 74 | { 75 | int a; // 0 76 | char b[MAX_CHAR_LEN]; // 1 77 | int c[C_ROW_NUM]; // 2,3,4 78 | // ... 79 | } T_ParaData; 80 | typedef enum 81 | { 82 | // 从 0 开始,连续 83 | PARA_A = 0, 84 | PARA_B , 85 | PARA_C1 ,//2,c在结构体中的起始位置序号 86 | PARA_C2 , 87 | PARA_C3, 88 | }E_PARA; 89 | // 90 | #define C_OFFSET (PARA_C1) 91 | // 上述参数类型中变量的数量 92 | //#define PARA_NUM (6) 93 | 94 | 95 | /* 实时数据,全部显示为整形,实际情况根据其精度进行处理。只读 96 | SNMP中NMS的显示由对象OID语法控制 97 | 后面的注释数字表示该变量在该数据类型部分的共享内存中的位置——唯一。如实时数据共享位置的起始地址为 98 | 0x1234,那么0x1234+0就表示变量a的地址 99 | */ 100 | 101 | 102 | /*实时数据:模拟整形,字符型,简单表多行多列 */ 103 | #define GROUP_NUM (2)// 示例某个组-表格列元素-两行两列 104 | struct _aGroup 105 | { 106 | int x; 107 | int y; 108 | // ... 109 | }; 110 | 111 | /* 112 | 序号No. x y 113 | 第一行 0 1 114 | 第二行 2 3 115 | z: 4 116 | */ 117 | typedef struct 118 | { 119 | struct _aGroup xy[GROUP_NUM]; 120 | int z; // 4 121 | // ... 122 | } T_RealData; 123 | typedef enum 124 | { 125 | // 从 0 开始,连续 126 | XY0X = 0, 127 | XY0Y , 128 | XY1X ,//2 129 | XY1Y , 130 | REALZ, 131 | }E_REALTIMEDATA; 132 | 133 | 134 | typedef struct 135 | { 136 | int alarm1; // 0 137 | //int alarm2; // 1 138 | char alarm2[MAX_CHAR_LEN]; 139 | int alarmCounter; // 2 140 | // ... 141 | } T_AlarmData; 142 | typedef enum 143 | { 144 | // 从 0 开始,连续 145 | ALARM1 = 0, 146 | ALARM2, 147 | ALARM_COUNTER,//2 148 | }E_ALARM; 149 | 150 | 151 | // 为了节省内存,该结构体并没有应用到实时数据中 152 | typedef struct 153 | { 154 | // 这两个需要手动维护。当然我们可以将由程序的一些前端脚本自动生成 155 | int iNo; // 参数的编号值(此数据在参数表中的索引,即从0开始) 156 | int iLen; // 数据的字节长度,如对于整形为sizeof(int)。 157 | U_Value uValue; //参数的值 158 | } T_ShmCellVal; 159 | 160 | #ifndef MIN 161 | #define MIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) 162 | #endif 163 | 164 | // 测试用 165 | int del_sem( void ); 166 | int del_shm( void ); 167 | 168 | 169 | int app_get_data(void* pStrVal, int dType); 170 | int app_set_data(void* pStrVal, int dType); 171 | int snmp_get_data( int dType, int no, int ll, void* pV ); 172 | int snmp_set_data( int dType, int no, int ll, void* pV ); 173 | 174 | 175 | void init_shm_sem_master(); 176 | void init_shm_sem_slave(); 177 | 178 | 179 | 180 | #ifdef __cplusplus 181 | } 182 | #endif /* __cplusplus */ 183 | 184 | #endif /* SNMPIPC_H */ 185 | 186 | -------------------------------------------------------------------------------- /ch10/nmsapp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | # http://www.cnblogs.com/sislcb/archive/2008/11/25/1340587.html 4 | # list --> set http://www.peterbe.com/plog/uniqifiers-benchmark/ 5 | # 系统列表:[ ip1,ip2,... ] 6 | # ip1列表:[snmpv3user,oids] 7 | # snmpv3user为固定的元组或字典:(v1,v2...){'user':v1,...} 8 | # oids为列表:[1.2.3, 1.2.4...] 9 | 10 | __ver__ = "V0.1 201411" 11 | __doc__ = """ 12 | 作者:张春强 13 | 功能:监控SNMP主机 14 | """ 15 | 16 | import netsnmp 17 | import ConfigParser 18 | import os 19 | import sys 20 | from query import PysnmpClass 21 | 22 | V3OPTIONS=('user','securityLevel','auth_passphrase','priv_passphrase') 23 | PEER_FILE = "/usr/local/etc/nmsapp/nmshosts.conf" 24 | GENERAL_OIDS_FILE = "/usr/local/etc/nmsapp/mibs/general/monitor.oids" 25 | 26 | def checkipv4addr(addr): 27 | try: 28 | if 'localhost' == str(addr): 29 | return True 30 | ss = addr.split('.') 31 | if len(ss) != 4: 32 | return False 33 | for x in ss: 34 | if not (0 <= int( x ) <= 255): 35 | return False 36 | except ValueError: 37 | return False 38 | return True 39 | 40 | def get_ip( alist=None ): 41 | """ 42 | 获取不重复的ip地址。 43 | 如果存在端口标记号':'则取该字符前部分内容作为ip 44 | """ 45 | ips=[] 46 | for ip in alist: 47 | ips.append(ip.split(':')[0]) 48 | 49 | if len( ips ) != len(set( ips )): 50 | print 'duplicated ip address!! exit(1)' 51 | sys.exit() 52 | return ips 53 | 54 | def mk_oidpath(aset): 55 | """ 56 | 生成各主机oids路径文件名。 57 | """ 58 | pth=[] 59 | for ip in aset: 60 | pth.append('/usr/local/etc/nmsapp/mibs/%s/monitor.oids'%(ip)) 61 | return pth 62 | 63 | def get_oidpath(host_list): 64 | """ 65 | 生成各主机oids路径文件名。 66 | """ 67 | return mk_oidpath( get_ip(host_list) ) 68 | 69 | def get_oids(f): 70 | """ 71 | 读取f文件中的oid:每行作为一个oid,忽略空行和#起始注释行 72 | 为了便于(其他程序)处理,统一使用数值型的OID. 73 | 当然netsnmp包也支持sysContact.0等形式的OID 74 | """ 75 | import re 76 | regex = re.compile(r'^(\.[1-9][1-9]*)+\.0$') 77 | oids=[] 78 | try: 79 | with open(f,'r') as pf: 80 | for ll in pf: 81 | if ll.split() and ll.split()[0] != '#': 82 | str = ll.split()[0] 83 | if regex.match(str): 84 | oids.append(str.split('\n')[0]) 85 | else: 86 | print 'oids: wrong format!!' 87 | except IOError as messg: 88 | print('open file failed!!\n'+str(messg)) 89 | return oids 90 | 91 | def get_conf_option(cfp,sec): 92 | """ 93 | 读取监控配置文件(nmshosts.conf)中某部分的选项 94 | """ 95 | adict = {} 96 | #print(sec) 97 | #print('---------------') 98 | global V3OPTIONS 99 | for o in V3OPTIONS: 100 | try: 101 | adict[o] = cfp.get(sec,o) 102 | except: 103 | print("%s:exception!!"%o) 104 | adict[o]= None 105 | return adict 106 | 107 | def get_all_sec_opt(cfp,host_list): 108 | """ 109 | 读取监控配置文件(nmshosts.conf)中的选项 110 | """ 111 | list_dict={} 112 | for h in host_list: 113 | list_dict[h]=get_conf_option(cfp,h) 114 | return list_dict 115 | 116 | def read_nmsapp_conf(): 117 | """ 118 | 读取监控配置文件(nmshosts.conf) 119 | """ 120 | cfp = ConfigParser.ConfigParser() 121 | global PEER_FILE 122 | cfp.read(PEER_FILE) 123 | 124 | ss = cfp.sections() 125 | host_list = [] 126 | 127 | for s in ss:#去除空格,取:前的字段 128 | if checkipv4addr( s.strip().split(':')[0] ): 129 | host_list.append( s.strip() ) 130 | #print host_list 131 | return (host_list, get_all_sec_opt(cfp,host_list) ) 132 | 133 | def read_oids(host_list): 134 | """ 135 | 读取所有主机待监控OID 136 | """ 137 | oid =[] 138 | oids_dict={} 139 | i = 0 140 | oid_paths = get_oidpath(host_list) 141 | #读取公共oid 142 | general_oids = get_oids(GENERAL_OIDS_FILE) 143 | for p in oid_paths: 144 | oid = get_oids(p) 145 | oids_dict[host_list[i]] = oid + general_oids 146 | i += 1 147 | return oids_dict 148 | #pass 149 | 150 | def get_oid_list_size(): 151 | pass 152 | 153 | def get_main_list_size(): 154 | pass 155 | 156 | def print_nmsapp_confs(host_list,host_oids,monitor_hosts_dict): 157 | print 'host_list:',host_list 158 | print '---------------------' 159 | print 'host_oids:',host_oids 160 | print '---------------------' 161 | print 'monitor_hosts_dict:',monitor_hosts_dict 162 | 163 | def print_dict_para(**kw): 164 | for k, v in kw.iteritems(): 165 | print k,'=',v 166 | 167 | def print_list_para(*ll): 168 | for l in ll: 169 | print l 170 | 171 | def main(): 172 | host_list=[] 173 | host_oids = {} 174 | monitor_hosts_dict={} 175 | 176 | (host_list, monitor_hosts_dict) = read_nmsapp_conf() 177 | #模拟 get_main_list_size() get_oid_list_size 178 | if (not host_list) or (not monitor_hosts_dict): 179 | sys.exit(0) 180 | host_oids = read_oids( host_list ) 181 | if not host_oids: 182 | sys.exit(0) 183 | #print_nmsapp_confs(host_list,host_oids,monitor_hosts_dict) 184 | 185 | qurerys = [] 186 | for h in host_list: 187 | #print_list_para( *host_oids[h] ) 188 | #print '-------------------------------' 189 | #print_dict_para(**monitor_hosts_dict[h]) 190 | qurerys.append( PysnmpClass(h,*host_oids[h], **monitor_hosts_dict[h]) ) 191 | 192 | for qq in qurerys: 193 | tt = qq.query() 194 | print 'hostname',tt.hostname 195 | print 'result:',tt.result 196 | 197 | 198 | if __name__=='__main__': 199 | main() 200 | 201 | 202 | -------------------------------------------------------------------------------- /ch9/BOOK-APP-MIB.mib: -------------------------------------------------------------------------------- 1 | BOOK-APP-MIB DEFINITIONS ::= BEGIN 2 | 3 | IMPORTS 4 | OBJECT-GROUP, NOTIFICATION-GROUP 5 | FROM SNMPv2-CONF 6 | enterprises, Integer32, OBJECT-TYPE, MODULE-IDENTITY, OBJECT-IDENTITY, Unsigned32, 7 | NOTIFICATION-TYPE 8 | FROM SNMPv2-SMI 9 | TEXTUAL-CONVENTION,DisplayString 10 | FROM SNMPv2-TC; 11 | 12 | bookAppMib MODULE-IDENTITY 13 | LAST-UPDATED "201409121341Z" 14 | ORGANIZATION "org" 15 | CONTACT-INFO "xtdwxk@gmail.com" 16 | DESCRIPTION 17 | "demo for my book(In-depth understanding of Net-SNMP)" 18 | REVISION "201409121341Z" 19 | DESCRIPTION "demo" 20 | ::= { netSnmpPlaypen 1 } 21 | 22 | 23 | netSnmp OBJECT IDENTIFIER ::= { enterprises 8072} 24 | netSnmpExperimental OBJECT IDENTIFIER ::= { netSnmp 9999 } 25 | netSnmpPlaypen OBJECT IDENTIFIER ::= { netSnmpExperimental 9999 } 26 | 27 | -- 28 | -- Textual conventions 29 | -- 30 | Float1TypeTC ::= TEXTUAL-CONVENTION 31 | DISPLAY-HINT 32 | "d-1" 33 | STATUS current 34 | DESCRIPTION 35 | "Description." 36 | SYNTAX Integer32 37 | 38 | -- 39 | -- Node definitions 40 | -- 41 | 42 | realTimeData OBJECT-GROUP 43 | OBJECTS { realTimeDataX1, realTimeDataY2,realTimeDataZ } 44 | STATUS current 45 | DESCRIPTION 46 | "Real data group." 47 | ::= { bookAppMib 1 } 48 | 49 | 50 | parameter OBJECT-GROUP 51 | OBJECTS { parameterA, parameterB, parameterC1} 52 | STATUS current 53 | DESCRIPTION 54 | "Parameter data group." 55 | ::= { bookAppMib 2 } 56 | 57 | 58 | notificationObjs OBJECT IDENTIFIER::= { bookAppMib 11 } 59 | 60 | notificationGroup NOTIFICATION-GROUP 61 | NOTIFICATIONS { sysAlarmNotify ,alarm1,alarm2 } 62 | STATUS current 63 | DESCRIPTION 64 | "Notification group." 65 | ::= { bookAppMib 3 } 66 | 67 | realTimeDataTable OBJECT-TYPE 68 | SYNTAX SEQUENCE OF RealTimeDataEntry 69 | MAX-ACCESS not-accessible 70 | STATUS current 71 | DESCRIPTION 72 | "Description." 73 | ::= { realTimeData 1 } 74 | 75 | realTimeDataEntry OBJECT-TYPE 76 | SYNTAX RealTimeDataEntry 77 | MAX-ACCESS not-accessible 78 | STATUS current 79 | DESCRIPTION 80 | "Description." 81 | INDEX { realTimeDataIndex } 82 | ::= { realTimeDataTable 1 } 83 | 84 | RealTimeDataEntry ::= 85 | SEQUENCE { 86 | realTimeDataIndex 87 | Integer32, 88 | realTimeDataX1 89 | Integer32, 90 | realTimeDataY2 91 | Integer32 92 | } 93 | 94 | realTimeDataIndex OBJECT-TYPE 95 | SYNTAX Integer32 (1..65536) 96 | MAX-ACCESS not-accessible 97 | STATUS current 98 | DESCRIPTION 99 | "Index." 100 | ::= { realTimeDataEntry 1 } 101 | 102 | realTimeDataX1 OBJECT-TYPE 103 | SYNTAX Integer32 (1..65536) 104 | MAX-ACCESS read-only 105 | STATUS current 106 | DESCRIPTION 107 | "realTimeDataX1." 108 | ::= { realTimeDataEntry 2 } 109 | 110 | realTimeDataY2 OBJECT-TYPE 111 | SYNTAX Integer32 (1..65536) 112 | MAX-ACCESS read-only 113 | STATUS current 114 | DESCRIPTION 115 | "realTimeDataY2." 116 | ::= { realTimeDataEntry 3 } 117 | 118 | realTimeDataZ OBJECT-TYPE 119 | SYNTAX Float1TypeTC 120 | MAX-ACCESS read-only 121 | STATUS current 122 | DESCRIPTION 123 | "realTimeDataZ." 124 | ::= { realTimeData 2 } 125 | 126 | 127 | parameterA OBJECT-TYPE 128 | SYNTAX Integer32 129 | MAX-ACCESS read-write 130 | STATUS current 131 | DESCRIPTION 132 | "parameterA." 133 | ::= { parameter 1 } 134 | 135 | parameterB OBJECT-TYPE 136 | SYNTAX DisplayString 137 | MAX-ACCESS read-write 138 | STATUS current 139 | DESCRIPTION 140 | "parameterB:max lenght is 32 char!" 141 | ::= { parameter 2 } 142 | 143 | parameterTable OBJECT-TYPE 144 | SYNTAX SEQUENCE OF ParameterEntry 145 | MAX-ACCESS not-accessible 146 | STATUS current 147 | DESCRIPTION 148 | "Description." 149 | ::= { parameter 3 } 150 | 151 | parameterEntry OBJECT-TYPE 152 | SYNTAX ParameterEntry 153 | MAX-ACCESS not-accessible 154 | STATUS current 155 | DESCRIPTION 156 | "Description." 157 | INDEX { parameterIndex } 158 | ::= { parameterTable 1 } 159 | 160 | ParameterEntry ::= 161 | SEQUENCE { 162 | parameterIndex 163 | Integer32, 164 | parameterC1 165 | Integer32 166 | } 167 | 168 | parameterIndex OBJECT-TYPE 169 | SYNTAX Integer32 (1..65536) 170 | MAX-ACCESS not-accessible 171 | STATUS current 172 | DESCRIPTION 173 | "Index." 174 | ::= { parameterEntry 1 } 175 | 176 | parameterC1 OBJECT-TYPE 177 | SYNTAX Integer32 (1..65536) 178 | MAX-ACCESS read-write 179 | STATUS current 180 | DESCRIPTION 181 | "parameterC1." 182 | ::= { parameterEntry 2 } 183 | 184 | sysAlarms OBJECT-IDENTITY 185 | STATUS current 186 | DESCRIPTION 187 | "notification node for system alarms." 188 | ::= { notificationGroup 0 } 189 | 190 | sysAlarmNotify NOTIFICATION-TYPE 191 | OBJECTS { alarmCounter,alarm1,alarm2} 192 | STATUS current 193 | DESCRIPTION 194 | "System Alarm Notify." 195 | ::= { sysAlarms 1 } 196 | 197 | alarm1 OBJECT-TYPE 198 | SYNTAX Integer32 199 | MAX-ACCESS accessible-for-notify 200 | STATUS current 201 | DESCRIPTION 202 | "for notification." 203 | ::= { notificationObjs 1 } 204 | 205 | alarm2 OBJECT-TYPE 206 | SYNTAX DisplayString 207 | MAX-ACCESS accessible-for-notify 208 | STATUS current 209 | DESCRIPTION 210 | "for notification." 211 | ::= { notificationObjs 2 } 212 | 213 | alarmCounter OBJECT-TYPE 214 | SYNTAX Integer32 215 | MAX-ACCESS read-write 216 | STATUS current 217 | DESCRIPTION 218 | "for notification count." 219 | ::= { notificationObjs 3 } 220 | 221 | 222 | END -------------------------------------------------------------------------------- /ch4/BOOK-EXAMPLE-MIB(original).my: -------------------------------------------------------------------------------- 1 | -- 2 | -- BOOK-EXAMPLE-MIB.my 3 | -- MIB generated by MG-SOFT Visual MIB Builder Version 6.0 Build 88 4 | -- Monday, April 12, 2014 at 18:53:08 5 | -- 6 | 7 | BOOK-EXAMPLE-MIB DEFINITIONS ::= BEGIN 8 | 9 | IMPORTS 10 | OBJECT-GROUP, NOTIFICATION-GROUP 11 | FROM SNMPv2-CONF 12 | enterprises, Integer32, OBJECT-TYPE, MODULE-IDENTITY, OBJECT-IDENTITY, Unsigned32, 13 | NOTIFICATION-TYPE 14 | FROM SNMPv2-SMI 15 | TEXTUAL-CONVENTION,DisplayString 16 | FROM SNMPv2-TC; 17 | 18 | 19 | -- 1.3.6.1.4.1.9999 20 | bookexampleMib MODULE-IDENTITY 21 | LAST-UPDATED "201404121341Z" -- April 12, 2014 at 13:41 GMT 22 | ORGANIZATION 23 | "BookForExample." 24 | CONTACT-INFO 25 | "Contact-info." 26 | DESCRIPTION 27 | "Description." 28 | ::= { enterprises 9999 } 29 | 30 | 31 | 32 | -- 33 | -- Type definitions 34 | -- 35 | 36 | ByteINT ::= INTEGER (0..255) 37 | 38 | 39 | -- 40 | -- Textual conventions 41 | -- 42 | 43 | Float1TypeTC ::= TEXTUAL-CONVENTION 44 | DISPLAY-HINT 45 | "d-1" 46 | STATUS current 47 | DESCRIPTION 48 | "Description." 49 | SYNTAX Integer32 50 | 51 | 52 | -- 53 | -- Node definitions 54 | -- 55 | 56 | -- 1.3.6.1.4.1.9999.1 57 | exampleNotifications OBJECT-IDENTITY 58 | STATUS current 59 | DESCRIPTION 60 | "Description." 61 | ::= { bookexampleMib 1 } 62 | 63 | 64 | -- 1.3.6.1.4.1.9999.1.1 65 | exampleNotify1 NOTIFICATION-TYPE 66 | STATUS current 67 | DESCRIPTION 68 | "Description." 69 | ::= { exampleNotifications 1 } 70 | 71 | 72 | -- 1.3.6.1.4.1.9999.3 73 | exampleObject OBJECT-IDENTITY 74 | STATUS current 75 | DESCRIPTION 76 | "Description." 77 | ::= { bookexampleMib 3 } 78 | 79 | 80 | -- 1.3.6.1.4.1.9999.3.1 81 | exampleObject1 OBJECT-TYPE 82 | SYNTAX Integer32 83 | MAX-ACCESS read-only 84 | STATUS current 85 | DESCRIPTION 86 | "Example:Integer32." 87 | ::= { exampleObject 1 } 88 | 89 | 90 | -- 1.3.6.1.4.1.9999.3.2 91 | exampleObject2 OBJECT-TYPE 92 | SYNTAX ByteINT 93 | MAX-ACCESS read-write 94 | STATUS current 95 | DESCRIPTION 96 | "Example:ByteINT." 97 | ::= { exampleObject 2 } 98 | 99 | 100 | -- 1.3.6.1.4.1.9999.3.3 101 | exampleObject3 OBJECT-TYPE 102 | SYNTAX Float1TypeTC 103 | MAX-ACCESS read-write 104 | STATUS current 105 | DESCRIPTION 106 | "Example:Float1TypeTC." 107 | ::= { exampleObject 3 } 108 | 109 | -- 1.3.6.1.4.1.9999.3.4 110 | exampleObject4 OBJECT-TYPE 111 | SYNTAX DisplayString 112 | MAX-ACCESS read-write 113 | STATUS current 114 | DESCRIPTION 115 | "Example:DisplayString." 116 | ::= { exampleObject 4 } 117 | 118 | -- 1.3.6.1.4.1.9999.3.9 119 | simpleTable OBJECT-TYPE 120 | SYNTAX SEQUENCE OF SimpleEntry 121 | MAX-ACCESS not-accessible 122 | STATUS current 123 | DESCRIPTION 124 | "Description." 125 | ::= { exampleObject 9 } 126 | 127 | 128 | -- 1.3.6.1.4.1.9999.3.9.1 129 | simpleEntry OBJECT-TYPE 130 | SYNTAX SimpleEntry 131 | MAX-ACCESS not-accessible 132 | STATUS current 133 | DESCRIPTION 134 | "Description." 135 | INDEX { simpleTbColum1 } 136 | ::= { simpleTable 1 } 137 | 138 | 139 | SimpleEntry ::= 140 | SEQUENCE { 141 | simpleTbColum1 142 | Integer32, 143 | simpleTbColum2 144 | Integer32 145 | } 146 | 147 | -- 1.3.6.1.4.1.9999.3.9.1.1 148 | simpleTbColum1 OBJECT-TYPE 149 | SYNTAX Integer32 (1..65536) 150 | MAX-ACCESS read-only 151 | STATUS current 152 | DESCRIPTION 153 | "Description." 154 | ::= { simpleEntry 1 } 155 | 156 | 157 | -- 1.3.6.1.4.1.9999.3.9.1.2 158 | simpleTbColum2 OBJECT-TYPE 159 | SYNTAX Integer32 160 | MAX-ACCESS read-write 161 | STATUS current 162 | DESCRIPTION 163 | "Description." 164 | ::= { simpleEntry 2 } 165 | 166 | -- 1.3.6.1.4.1.9999.3.11 167 | generalTable OBJECT-TYPE 168 | SYNTAX SEQUENCE OF GeneralEntry 169 | MAX-ACCESS not-accessible 170 | STATUS current 171 | DESCRIPTION 172 | "Description." 173 | ::= { exampleObject 11 } 174 | 175 | 176 | -- 1.3.6.1.4.1.9999.3.11.1 177 | generalEntry OBJECT-TYPE 178 | SYNTAX GeneralEntry 179 | MAX-ACCESS not-accessible 180 | STATUS current 181 | DESCRIPTION 182 | "Description." 183 | INDEX { generalTbColum1,generalTbColum2 } 184 | ::= { generalTable 1 } 185 | 186 | 187 | GeneralEntry ::= 188 | SEQUENCE { 189 | generalTbColum1 190 | Unsigned32, 191 | generalTbColum2 192 | Unsigned32, 193 | generalTbColum3 194 | DisplayString, 195 | generalTbColum4 196 | Integer32 197 | } 198 | 199 | -- 1.3.6.1.4.1.9999.3.9.1.1 200 | generalTbColum1 OBJECT-TYPE 201 | SYNTAX Unsigned32 202 | MAX-ACCESS read-only 203 | STATUS current 204 | DESCRIPTION 205 | "Description." 206 | ::= { generalEntry 1 } 207 | 208 | 209 | -- 1.3.6.1.4.1.9999.3.11.1.2 210 | generalTbColum2 OBJECT-TYPE 211 | SYNTAX Unsigned32 212 | MAX-ACCESS read-only 213 | STATUS current 214 | DESCRIPTION 215 | "Description." 216 | ::= { generalEntry 2 } 217 | 218 | -- 1.3.6.1.4.1.9999.3.11.1.3 219 | generalTbColum3 OBJECT-TYPE 220 | SYNTAX DisplayString 221 | MAX-ACCESS read-write 222 | STATUS current 223 | DESCRIPTION 224 | "Description." 225 | ::= { generalEntry 3 } 226 | 227 | -- 1.3.6.1.4.1.9999.3.11.1.4 228 | generalTbColum4 OBJECT-TYPE 229 | SYNTAX Integer32 230 | MAX-ACCESS read-write 231 | STATUS current 232 | DESCRIPTION 233 | "Description." 234 | ::= { generalEntry 4 } 235 | 236 | -- 1.3.6.1.4.1.9999.4 237 | objectGroup OBJECT-GROUP 238 | OBJECTS { exampleObject1, exampleObject2, exampleObject3, simpleTbColum1, simpleTbColum2,generalTbColum3, 239 | generalTbColum4 240 | } 241 | STATUS current 242 | DESCRIPTION 243 | "Description." 244 | ::= { bookexampleMib 4 } 245 | 246 | 247 | -- 1.3.6.1.4.1.9999.5 248 | notificationGroup NOTIFICATION-GROUP 249 | NOTIFICATIONS { exampleNotify1 } 250 | STATUS current 251 | DESCRIPTION 252 | "Description." 253 | ::= { bookexampleMib 5 } 254 | 255 | 256 | 257 | END 258 | 259 | -- 260 | -- BOOK-EXAMPLE-MIB.my 261 | -- 262 | -------------------------------------------------------------------------------- /ch7/snmpd.conf: -------------------------------------------------------------------------------- 1 | ########################################################################### 2 | # 3 | # snmpd.conf 4 | # 5 | # - created by the snmpconf configuration program 6 | # 7 | ########################################################################### 8 | # SECTION: System Information Setup 9 | # 10 | # This section defines some of the information reported in 11 | # the "system" mib group in the mibII tree. 12 | 13 | # syslocation: The [typically physical] location of the system. 14 | # Note that setting this value here means that when trying to 15 | # perform an snmp SET operation to the sysLocation.0 variable will make 16 | # the agent return the "notWritable" error code. IE, including 17 | # this token in the snmpd.conf file will disable write access to 18 | # the variable. 19 | # arguments: location_string 20 | 21 | syslocation shenzhenxx 22 | 23 | # syscontact: The contact information for the administrator 24 | # Note that setting this value here means that when trying to 25 | # perform an snmp SET operation to the sysContact.0 variable will make 26 | # the agent return the "notWritable" error code. IE, including 27 | # this token in the snmpd.conf file will disable write access to 28 | # the variable. 29 | # arguments: contact_string 30 | 31 | syscontact xtdwxk@gmail.com 32 | 33 | # sysservices: The proper value for the sysServices object. 34 | # arguments: sysservices_number 35 | 36 | sysservices 76 37 | 38 | 39 | 40 | 41 | 42 | 43 | ########################################################################### 44 | # SECTION: Monitor Various Aspects of the Running Host 45 | # 46 | # The following check up on various aspects of a host. 47 | 48 | # proc: Check for processes that should be running. 49 | # proc NAME [MAX=0] [MIN=0] 50 | # 51 | # NAME: the name of the process to check for. It must match 52 | # exactly (ie, http will not find httpd processes). 53 | # MAX: the maximum number allowed to be running. Defaults to 0. 54 | # MIN: the minimum number to be running. Defaults to 0. 55 | # 56 | # The results are reported in the prTable section of the UCD-SNMP-MIB tree 57 | # Special Case: When the min and max numbers are both 0, it assumes 58 | # you want a max of infinity and a min of 1. 59 | 60 | proc snmpd 61 | #proc init 1 1 62 | proc httpd 1 8 63 | #proc httpd 1 0 64 | 65 | # disk: Check for disk space usage of a partition. 66 | # The agent can check the amount of available disk space, and make 67 | # sure it is above a set limit. 68 | # 69 | # disk PATH [MIN=100000] 70 | # 71 | # PATH: mount path to the disk in question. 72 | # MIN: Disks with space below this value will have the Mib's errorFlag set. 73 | # Can be a raw integer value (units of kB) or a percentage followed by the % 74 | # symbol. Default value = 100000. 75 | # 76 | # The results are reported in the dskTable section of the UCD-SNMP-MIB tree 77 | 78 | disk / 30% 79 | 80 | # load: Check for unreasonable load average values. 81 | # Watch the load average levels on the machine. 82 | # 83 | # load [1MAX=12.0] [5MAX=12.0] [15MAX=12.0] 84 | # 85 | # 1MAX: If the 1 minute load average is above this limit at query 86 | # time, the errorFlag will be set. 87 | # 5MAX: Similar, but for 5 min average. 88 | # 15MAX: Similar, but for 15 min average. 89 | # 90 | # The results are reported in the laTable section of the UCD-SNMP-MIB tree 91 | 92 | load 7 6 5 93 | 94 | # file: Check on the size of a file. 95 | # Display a files size statistics. 96 | # If it grows to be too large, report an error about it. 97 | # 98 | # file /path/to/file [maxsize_in_kilobytes] 99 | # 100 | # if maxsize is not specified, assume only size reporting is needed. 101 | # 102 | # The results are reported in the fileTable section of the UCD-SNMP-MIB tree 103 | 104 | file /var/log/snmpd.log 1024 105 | file /home/chanson/Documents/test-file-size 2 106 | 107 | 108 | 109 | ########################################################################### 110 | # SECTION: Trap Destinations 111 | # 112 | # Here we define who the agent will send traps to. 113 | 114 | # trapsink: A SNMPv1 trap receiver 115 | # arguments: host [community] [portnum] 116 | 117 | trapsink 192.168.43.147 118 | 119 | # trap2sink: A SNMPv2c trap receiver 120 | # arguments: host [community] [portnum] 121 | 122 | trap2sink 192.168.43.147 123 | 124 | # informsink: A SNMPv2c inform (acknowledged trap) receiver 125 | # arguments: host [community] [portnum] 126 | 127 | informsink 192.168.43.147 128 | informsink localhost 129 | 130 | # trapcommunity: Default trap sink community to use 131 | # arguments: community-string 132 | 133 | trapcommunity public 134 | 135 | # authtrapenable: Should we send traps when authentication failures occur 136 | # arguments: 1 | 2 (1 = yes, 2 = no) 137 | 138 | authtrapenable 1 139 | 140 | 141 | 142 | 143 | 144 | 145 | ########################################################################### 146 | # SECTION: Access Control Setup 147 | # 148 | # This section defines who is allowed to talk to your running 149 | # snmp agent. 150 | 151 | # rwuser: a SNMPv3 read-write user 152 | # arguments: user [noauth|auth|priv] [restriction_oid] 153 | 154 | rwuser admin auth 155 | 156 | # rouser: a SNMPv3 read-only user 157 | # arguments: user [noauth|auth|priv] [restriction_oid] 158 | 159 | rouser roNetSNMP auth .1.3.6.1.4.1.8072 160 | 161 | # rocommunity: a SNMPv1/SNMPv2c read-only access community name 162 | # arguments: community [default|hostname|network/bits] [oid] 163 | 164 | rocommunity public 165 | 166 | # rwcommunity: a SNMPv1/SNMPv2c read-write access community name 167 | # arguments: community [default|hostname|network/bits] [oid] 168 | 169 | rwcommunity private 127.0.0.1 170 | rwcommunity privateHigh 171 | 172 | ######## test v3 173 | rouser noAuth_User noauth system 174 | rouser MD5_User authNoPriv system 175 | rwuser MD5_DES_User authpriv system 176 | rwuser MD5_DES_User2 authPriv system 177 | 178 | #### 179 | agentuser chanson 180 | 181 | #### monitor all disk or use:disk 182 | includeAllDisks 183 | 184 | ## extend 185 | #extend .1.3.6.1.4.1.8072.9999.9999.1 monitor_tcp_udp /mnt/hgfs/centosShare/sh/tcp_udp_connect.sh 186 | 187 | #extend .1.3.6.1.4.1.2021.255 monitor_udp /root/sh/tcpCount.sh 188 | #exec .1.3.6.1.4.1.2021.255 monitor_udp /root/sh/tcpCount.sh 189 | 190 | #exec defunct_count /mnt/hgfs/centosShare/sh/defunct_count.sh 191 | #extend defunct_count /mnt/hgfs/centosShare/sh/defunct_count.sh 192 | extend mem_usage /mnt/hgfs/centosShare/sh/mem_usage.sh 193 | #extend tcp_time_wait_count /mnt/hgfs/centosShare/sh/tcp_time_wait_count.sh 194 | 195 | extend udp_count /mnt/hgfs/centosShare/sh/udp_count.sh 196 | extend test_two_echo /mnt/hgfs/centosShare/sh/testTwoEcho.sh 197 | 198 | logmatch apache-error-log /etc/httpd/logs/error_log-%Y%m%d 400 [error] 199 | -------------------------------------------------------------------------------- /ch4/BOOK-EXAMPLE-MIB.my: -------------------------------------------------------------------------------- 1 | -- 2 | -- BOOK-EXAMPLE-MIB.my 3 | -- MIB generated by MG-SOFT Visual MIB Builder Version 6.0 Build 88 4 | -- Monday, April 12, 2014 at 18:53:08 5 | -- 6 | 7 | BOOK-EXAMPLE-MIB DEFINITIONS ::= BEGIN 8 | 9 | IMPORTS 10 | OBJECT-GROUP, NOTIFICATION-GROUP 11 | FROM SNMPv2-CONF 12 | enterprises, Integer32, OBJECT-TYPE, MODULE-IDENTITY, OBJECT-IDENTITY, Unsigned32, 13 | NOTIFICATION-TYPE 14 | FROM SNMPv2-SMI 15 | TEXTUAL-CONVENTION,DisplayString 16 | FROM SNMPv2-TC; 17 | 18 | 19 | -- 1.3.6.1.4.1.9999 20 | bookexampleMib MODULE-IDENTITY 21 | LAST-UPDATED "201404121341Z" -- April 12, 2014 at 13:41 GMT 22 | ORGANIZATION 23 | "BookForExample." 24 | CONTACT-INFO 25 | "Contact-info." 26 | DESCRIPTION 27 | "Description." 28 | ::= { enterprises 9999 } 29 | 30 | 31 | 32 | -- 33 | -- Type definitions 34 | -- 35 | 36 | ByteINT ::= INTEGER (0..255) 37 | 38 | 39 | -- 40 | -- Textual conventions 41 | -- 42 | 43 | Float1TypeTC ::= TEXTUAL-CONVENTION 44 | DISPLAY-HINT 45 | "d-1" 46 | STATUS current 47 | DESCRIPTION 48 | "Description." 49 | SYNTAX Integer32 50 | 51 | 52 | -- 53 | -- Node definitions 54 | -- 55 | 56 | -- 1.3.6.1.4.1.9999.1 57 | exampleNotifications OBJECT-IDENTITY 58 | STATUS current 59 | DESCRIPTION 60 | "notification tree." 61 | ::= { bookexampleMib 1 } 62 | 63 | -- 1.3.6.1.4.1.9999.1.0 64 | exampleNotification OBJECT-IDENTITY 65 | STATUS current 66 | DESCRIPTION 67 | "notification node." 68 | ::= { exampleNotifications 0 } 69 | 70 | 71 | -- 1.3.6.1.4.1.9999.1.0.1 72 | exampleNotify1 NOTIFICATION-TYPE 73 | OBJECTS { exampleNotifyObj1 } 74 | STATUS current 75 | DESCRIPTION 76 | "Description." 77 | ::= { exampleNotification 1 } 78 | 79 | 80 | -- 1.3.6.1.4.1.9999.3 81 | exampleObject OBJECT-IDENTITY 82 | STATUS current 83 | DESCRIPTION 84 | "Description." 85 | ::= { bookexampleMib 3 } 86 | 87 | 88 | -- 1.3.6.1.4.1.9999.3.1 89 | exampleObject1 OBJECT-TYPE 90 | SYNTAX Integer32 91 | MAX-ACCESS read-only 92 | STATUS current 93 | DESCRIPTION 94 | "Example:Integer32." 95 | ::= { exampleObject 1 } 96 | 97 | 98 | -- 1.3.6.1.4.1.9999.3.2 99 | exampleObject2 OBJECT-TYPE 100 | SYNTAX ByteINT 101 | MAX-ACCESS read-write 102 | STATUS current 103 | DESCRIPTION 104 | "Example:ByteINT." 105 | ::= { exampleObject 2 } 106 | 107 | 108 | -- 1.3.6.1.4.1.9999.3.3 109 | exampleObject3 OBJECT-TYPE 110 | SYNTAX Float1TypeTC 111 | MAX-ACCESS read-write 112 | STATUS current 113 | DESCRIPTION 114 | "Example:Float1TypeTC." 115 | ::= { exampleObject 3 } 116 | 117 | -- 1.3.6.1.4.1.9999.3.4 118 | exampleObject4 OBJECT-TYPE 119 | SYNTAX DisplayString 120 | MAX-ACCESS read-write 121 | STATUS current 122 | DESCRIPTION 123 | "Example:DisplayString." 124 | ::= { exampleObject 4 } 125 | 126 | -- 1.3.6.1.4.1.9999.3.9 127 | simpleTable OBJECT-TYPE 128 | SYNTAX SEQUENCE OF SimpleEntry 129 | MAX-ACCESS not-accessible 130 | STATUS current 131 | DESCRIPTION 132 | "Description." 133 | ::= { exampleObject 9 } 134 | 135 | 136 | -- 1.3.6.1.4.1.9999.3.9.1 137 | simpleEntry OBJECT-TYPE 138 | SYNTAX SimpleEntry 139 | MAX-ACCESS not-accessible 140 | STATUS current 141 | DESCRIPTION 142 | "Description." 143 | INDEX { simpleTbColum1 } 144 | ::= { simpleTable 1 } 145 | 146 | 147 | SimpleEntry ::= 148 | SEQUENCE { 149 | simpleTbColum1 150 | Integer32, 151 | simpleTbColum2 152 | Integer32 153 | } 154 | 155 | -- 1.3.6.1.4.1.9999.3.9.1.1 156 | simpleTbColum1 OBJECT-TYPE 157 | SYNTAX Integer32 (1..65536) 158 | MAX-ACCESS read-only 159 | STATUS current 160 | DESCRIPTION 161 | "Description." 162 | ::= { simpleEntry 1 } 163 | 164 | 165 | -- 1.3.6.1.4.1.9999.3.9.1.2 166 | simpleTbColum2 OBJECT-TYPE 167 | SYNTAX Integer32 168 | MAX-ACCESS read-write 169 | STATUS current 170 | DESCRIPTION 171 | "Description." 172 | ::= { simpleEntry 2 } 173 | 174 | -- 1.3.6.1.4.1.9999.3.11 175 | generalTable OBJECT-TYPE 176 | SYNTAX SEQUENCE OF GeneralEntry 177 | MAX-ACCESS not-accessible 178 | STATUS current 179 | DESCRIPTION 180 | "Description." 181 | ::= { exampleObject 11 } 182 | 183 | 184 | -- 1.3.6.1.4.1.9999.3.11.1 185 | generalEntry OBJECT-TYPE 186 | SYNTAX GeneralEntry 187 | MAX-ACCESS not-accessible 188 | STATUS current 189 | DESCRIPTION 190 | "Description." 191 | INDEX { generalTbColum1,generalTbColum2 } 192 | ::= { generalTable 1 } 193 | 194 | 195 | GeneralEntry ::= 196 | SEQUENCE { 197 | generalTbColum1 198 | Unsigned32, 199 | generalTbColum2 200 | Unsigned32, 201 | generalTbColum3 202 | DisplayString, 203 | generalTbColum4 204 | Integer32 205 | } 206 | 207 | -- 1.3.6.1.4.1.9999.3.9.1.1 208 | generalTbColum1 OBJECT-TYPE 209 | SYNTAX Unsigned32 210 | MAX-ACCESS read-only 211 | STATUS current 212 | DESCRIPTION 213 | "Description." 214 | ::= { generalEntry 1 } 215 | 216 | 217 | -- 1.3.6.1.4.1.9999.3.11.1.2 218 | generalTbColum2 OBJECT-TYPE 219 | SYNTAX Unsigned32 220 | MAX-ACCESS read-only 221 | STATUS current 222 | DESCRIPTION 223 | "Description." 224 | ::= { generalEntry 2 } 225 | 226 | -- 1.3.6.1.4.1.9999.3.11.1.3 227 | generalTbColum3 OBJECT-TYPE 228 | SYNTAX DisplayString 229 | MAX-ACCESS read-write 230 | STATUS current 231 | DESCRIPTION 232 | "Description." 233 | ::= { generalEntry 3 } 234 | 235 | -- 1.3.6.1.4.1.9999.3.11.1.4 236 | generalTbColum4 OBJECT-TYPE 237 | SYNTAX Integer32 238 | MAX-ACCESS read-write 239 | STATUS current 240 | DESCRIPTION 241 | "Description." 242 | ::= { generalEntry 4 } 243 | 244 | -- 1.3.6.1.4.1.9999.4 245 | objectGroup OBJECT-GROUP 246 | OBJECTS { exampleObject1, exampleObject2, exampleObject3, simpleTbColum1, simpleTbColum2,generalTbColum3, 247 | generalTbColum4 248 | } 249 | STATUS current 250 | DESCRIPTION 251 | "Description." 252 | ::= { bookexampleMib 4 } 253 | 254 | 255 | -- 1.3.6.1.4.1.9999.5 256 | notificationGroup NOTIFICATION-GROUP 257 | NOTIFICATIONS { exampleNotify1 ,exampleNotifyObj1} 258 | STATUS current 259 | DESCRIPTION 260 | "Description." 261 | ::= { bookexampleMib 5 } 262 | 263 | -- 1.3.6.1.4.1.9999.10 264 | notificationObjs OBJECT IDENTIFIER 265 | ::= { bookexampleMib 10 } 266 | 267 | -- 1.3.6.1.4.1.9999.10.1 268 | exampleNotifyObj1 OBJECT-TYPE 269 | SYNTAX Integer32 270 | MAX-ACCESS accessible-for-notify 271 | STATUS current 272 | DESCRIPTION 273 | "for notification." 274 | ::= { notificationObjs 1 } 275 | 276 | -- 1.3.6.1.4.1.9999.10.2 277 | exampleNotifyObj2 OBJECT-TYPE 278 | SYNTAX Integer32 279 | MAX-ACCESS accessible-for-notify 280 | STATUS current 281 | DESCRIPTION 282 | "optional for notification." 283 | ::= { notificationObjs 2 } 284 | 285 | 286 | END 287 | 288 | -- 289 | -- BOOK-EXAMPLE-MIB.my 290 | -- 291 | -------------------------------------------------------------------------------- /ch9/BOOK-EXAMPLE-MIB.my: -------------------------------------------------------------------------------- 1 | -- 2 | -- BOOK-EXAMPLE-MIB.my 3 | -- MIB generated by MG-SOFT Visual MIB Builder Version 6.0 Build 88 4 | -- Monday, April 12, 2014 at 18:53:08 5 | -- 6 | 7 | BOOK-EXAMPLE-MIB DEFINITIONS ::= BEGIN 8 | 9 | IMPORTS 10 | OBJECT-GROUP, NOTIFICATION-GROUP 11 | FROM SNMPv2-CONF 12 | enterprises, Integer32, OBJECT-TYPE, MODULE-IDENTITY, OBJECT-IDENTITY, Unsigned32, 13 | NOTIFICATION-TYPE 14 | FROM SNMPv2-SMI 15 | TEXTUAL-CONVENTION,DisplayString 16 | FROM SNMPv2-TC; 17 | 18 | 19 | -- 1.3.6.1.4.1.9999 20 | bookexampleMib MODULE-IDENTITY 21 | LAST-UPDATED "201404121341Z" -- April 12, 2014 at 13:41 GMT 22 | ORGANIZATION 23 | "BookForExample." 24 | CONTACT-INFO 25 | "Contact-info." 26 | DESCRIPTION 27 | "Description." 28 | ::= { enterprises 9999 } 29 | 30 | 31 | 32 | -- 33 | -- Type definitions 34 | -- 35 | 36 | ByteINT ::= INTEGER (0..255) 37 | 38 | 39 | -- 40 | -- Textual conventions 41 | -- 42 | 43 | Float1TypeTC ::= TEXTUAL-CONVENTION 44 | DISPLAY-HINT 45 | "d-1" 46 | STATUS current 47 | DESCRIPTION 48 | "Description." 49 | SYNTAX Integer32 50 | 51 | 52 | -- 53 | -- Node definitions 54 | -- 55 | 56 | -- 1.3.6.1.4.1.9999.1 57 | exampleNotifications OBJECT-IDENTITY 58 | STATUS current 59 | DESCRIPTION 60 | "notification tree." 61 | ::= { bookexampleMib 1 } 62 | 63 | -- 1.3.6.1.4.1.9999.1.0 64 | exampleNotification OBJECT-IDENTITY 65 | STATUS current 66 | DESCRIPTION 67 | "notification node." 68 | ::= { exampleNotifications 0 } 69 | 70 | 71 | -- 1.3.6.1.4.1.9999.1.0.1 72 | exampleNotify1 NOTIFICATION-TYPE 73 | OBJECTS { exampleNotifyObj1 } 74 | STATUS current 75 | DESCRIPTION 76 | "Description." 77 | ::= { exampleNotification 1 } 78 | 79 | 80 | -- 1.3.6.1.4.1.9999.3 81 | exampleObject OBJECT-IDENTITY 82 | STATUS current 83 | DESCRIPTION 84 | "Description." 85 | ::= { bookexampleMib 3 } 86 | 87 | 88 | -- 1.3.6.1.4.1.9999.3.1 89 | exampleObject1 OBJECT-TYPE 90 | SYNTAX Integer32 91 | MAX-ACCESS read-only 92 | STATUS current 93 | DESCRIPTION 94 | "Example:Integer32." 95 | ::= { exampleObject 1 } 96 | 97 | 98 | -- 1.3.6.1.4.1.9999.3.2 99 | exampleObject2 OBJECT-TYPE 100 | SYNTAX ByteINT 101 | MAX-ACCESS read-write 102 | STATUS current 103 | DESCRIPTION 104 | "Example:ByteINT." 105 | ::= { exampleObject 2 } 106 | 107 | 108 | -- 1.3.6.1.4.1.9999.3.3 109 | exampleObject3 OBJECT-TYPE 110 | SYNTAX Float1TypeTC 111 | MAX-ACCESS read-write 112 | STATUS current 113 | DESCRIPTION 114 | "Example:Float1TypeTC." 115 | ::= { exampleObject 3 } 116 | 117 | -- 1.3.6.1.4.1.9999.3.4 118 | exampleObject4 OBJECT-TYPE 119 | SYNTAX DisplayString 120 | MAX-ACCESS read-write 121 | STATUS current 122 | DESCRIPTION 123 | "Example:DisplayString." 124 | ::= { exampleObject 4 } 125 | 126 | -- 1.3.6.1.4.1.9999.3.9 127 | simpleTable OBJECT-TYPE 128 | SYNTAX SEQUENCE OF SimpleEntry 129 | MAX-ACCESS not-accessible 130 | STATUS current 131 | DESCRIPTION 132 | "Description." 133 | ::= { exampleObject 9 } 134 | 135 | 136 | -- 1.3.6.1.4.1.9999.3.9.1 137 | simpleEntry OBJECT-TYPE 138 | SYNTAX SimpleEntry 139 | MAX-ACCESS not-accessible 140 | STATUS current 141 | DESCRIPTION 142 | "Description." 143 | INDEX { simpleTbColum1 } 144 | ::= { simpleTable 1 } 145 | 146 | 147 | SimpleEntry ::= 148 | SEQUENCE { 149 | simpleTbColum1 150 | Integer32, 151 | simpleTbColum2 152 | Integer32 153 | } 154 | 155 | -- 1.3.6.1.4.1.9999.3.9.1.1 156 | simpleTbColum1 OBJECT-TYPE 157 | SYNTAX Integer32 (1..65536) 158 | MAX-ACCESS read-only 159 | STATUS current 160 | DESCRIPTION 161 | "Description." 162 | ::= { simpleEntry 1 } 163 | 164 | 165 | -- 1.3.6.1.4.1.9999.3.9.1.2 166 | simpleTbColum2 OBJECT-TYPE 167 | SYNTAX Integer32 168 | MAX-ACCESS read-write 169 | STATUS current 170 | DESCRIPTION 171 | "Description." 172 | ::= { simpleEntry 2 } 173 | 174 | -- 1.3.6.1.4.1.9999.3.11 175 | generalTable OBJECT-TYPE 176 | SYNTAX SEQUENCE OF GeneralEntry 177 | MAX-ACCESS not-accessible 178 | STATUS current 179 | DESCRIPTION 180 | "Description." 181 | ::= { exampleObject 11 } 182 | 183 | 184 | -- 1.3.6.1.4.1.9999.3.11.1 185 | generalEntry OBJECT-TYPE 186 | SYNTAX GeneralEntry 187 | MAX-ACCESS not-accessible 188 | STATUS current 189 | DESCRIPTION 190 | "Description." 191 | INDEX { generalTbColum1,generalTbColum2 } 192 | ::= { generalTable 1 } 193 | 194 | 195 | GeneralEntry ::= 196 | SEQUENCE { 197 | generalTbColum1 198 | Unsigned32, 199 | generalTbColum2 200 | Unsigned32, 201 | generalTbColum3 202 | DisplayString, 203 | generalTbColum4 204 | Integer32 205 | } 206 | 207 | -- 1.3.6.1.4.1.9999.3.9.1.1 208 | generalTbColum1 OBJECT-TYPE 209 | SYNTAX Unsigned32 210 | MAX-ACCESS read-only 211 | STATUS current 212 | DESCRIPTION 213 | "Description." 214 | ::= { generalEntry 1 } 215 | 216 | 217 | -- 1.3.6.1.4.1.9999.3.11.1.2 218 | generalTbColum2 OBJECT-TYPE 219 | SYNTAX Unsigned32 220 | MAX-ACCESS read-only 221 | STATUS current 222 | DESCRIPTION 223 | "Description." 224 | ::= { generalEntry 2 } 225 | 226 | -- 1.3.6.1.4.1.9999.3.11.1.3 227 | generalTbColum3 OBJECT-TYPE 228 | SYNTAX DisplayString 229 | MAX-ACCESS read-write 230 | STATUS current 231 | DESCRIPTION 232 | "Description." 233 | ::= { generalEntry 3 } 234 | 235 | -- 1.3.6.1.4.1.9999.3.11.1.4 236 | generalTbColum4 OBJECT-TYPE 237 | SYNTAX Integer32 238 | MAX-ACCESS read-write 239 | STATUS current 240 | DESCRIPTION 241 | "Description." 242 | ::= { generalEntry 4 } 243 | 244 | -- 1.3.6.1.4.1.9999.4 245 | objectGroup OBJECT-GROUP 246 | OBJECTS { exampleObject1, exampleObject2, exampleObject3, simpleTbColum1, simpleTbColum2,generalTbColum3, 247 | generalTbColum4 248 | } 249 | STATUS current 250 | DESCRIPTION 251 | "Description." 252 | ::= { bookexampleMib 4 } 253 | 254 | 255 | -- 1.3.6.1.4.1.9999.5 256 | notificationGroup NOTIFICATION-GROUP 257 | NOTIFICATIONS { exampleNotify1 ,exampleNotifyObj1} 258 | STATUS current 259 | DESCRIPTION 260 | "Description." 261 | ::= { bookexampleMib 5 } 262 | 263 | -- 1.3.6.1.4.1.9999.10 264 | notificationObjs OBJECT IDENTIFIER 265 | ::= { bookexampleMib 10 } 266 | 267 | -- 1.3.6.1.4.1.9999.10.1 268 | exampleNotifyObj1 OBJECT-TYPE 269 | SYNTAX Integer32 270 | MAX-ACCESS accessible-for-notify 271 | STATUS current 272 | DESCRIPTION 273 | "for notification." 274 | ::= { notificationObjs 1 } 275 | 276 | -- 1.3.6.1.4.1.9999.10.2 277 | exampleNotifyObj2 OBJECT-TYPE 278 | SYNTAX Integer32 279 | MAX-ACCESS accessible-for-notify 280 | STATUS current 281 | DESCRIPTION 282 | "optional for notification." 283 | ::= { notificationObjs 2 } 284 | 285 | 286 | END 287 | 288 | -- 289 | -- BOOK-EXAMPLE-MIB.my 290 | -- 291 | -------------------------------------------------------------------------------- /ch11/perl_mysql/mysql_agent.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl -w 2 | 3 | # mysql_agent.pl 4 | 5 | use v5.10; 6 | use DBI; 7 | use warnings; 8 | use NetSNMP::OID (':all'); 9 | use NetSNMP::agent(':all'); 10 | use NetSNMP::ASN(':all'); 11 | use NetSNMP::agent::default_store; 12 | use NetSNMP::default_store qw(:all); 13 | use SNMP; 14 | use feature qw(say); 15 | use Data::Dumper; 16 | 17 | 18 | # 父节点的OID 19 | # my $OID = '.1.3.6.1.4.1.8072.9999.9999.2.1'; 20 | my $regOID; # opt{oid} 对象(NetSNMP::OID) 21 | 22 | my %global_status = (); 23 | my $global_last_refresh = 0; # 上次更新时间 24 | my $running = 0; 25 | my %oids = (); # 字符型和数值型OID(NetSNMP::OID) 26 | my @ordKs; # 排序的oids 27 | my %orign_new = (); # 原始字符型和mib名 28 | my %oid_index = (); # 原始字符型和mib名 29 | 30 | my %opt = ( 31 | # daemon_pid => '/var/run/mysql-snmp.pid', 32 | # 父节点的OID 33 | oid => '.1.3.6.1.4.1.8072.9999.9999.2.1', 34 | refresh => 60, # 单位秒 #500 35 | dsn => "DBI:mysql:host=127.0.0.1;port=3306", 36 | user => "user", 37 | password => "password", 38 | verbose => 1 39 | ); 40 | 41 | sub dolog { 42 | my ($level, $msg) = @_; 43 | # syslog($level, $msg); 44 | print STDERR $msg . "\n" if ($opt{verbose}); 45 | } 46 | 47 | # 后台运行 48 | sub daemonize { 49 | } 50 | 51 | # 取数据 52 | sub get_mysql_show_status{ 53 | my ($dsn, $dbuser, $dbpass) = @_; 54 | my $cmd = "SHOW /*!50002 GLOBAL */ STATUS";# 执行的指令 55 | 56 | # 使用DBI链接数据库并执行“show global status”命令 57 | my $dbh = DBI->connect($dsn, $dbuser, $dbpass) 58 | or die("Unable to connect: $DBI::errstr\n");#数据库句柄 59 | my $result = $dbh->selectall_arrayref($cmd); 60 | # 断开链接 61 | $dbh->disconnect(); 62 | 63 | return ($result); # 返回数组?正确吗 64 | } 65 | 66 | sub get_mysql_info{ 67 | return get_mysql_show_status($opt{dsn}, $opt{user}, $opt{password}); 68 | } 69 | 70 | # 对应关系-只执行一次 71 | sub mk_oid_table{ 72 | my $i = 1; 73 | my $result = get_mysql_info(); 74 | foreach my $row (@$result) { 75 | my $mib_name = $row->[0] ; 76 | $mib_name =~ s/_(.)/\U$1\E/g; 77 | $orign_new{ $row->[0] } = "my$mib_name"; 78 | $oid_index{ $row->[0] } = $i; 79 | $i++; 80 | } 81 | 82 | } 83 | # 把$orign_new对应到表 84 | sub mk_oids{ 85 | my $i=1; 86 | # 构建 oids 表 87 | foreach my $name ( keys %orign_new ) { 88 | $oids{$regOID . ".$oid_index{$name}.0"} = { 89 | 'name' => $orign_new{$name}, 90 | 'oid' => new NetSNMP::OID($regOID . ".$oid_index{$name}.0") 91 | }; 92 | $i++; 93 | } 94 | # say Dumper(\%oids); 95 | } 96 | 97 | 98 | # 取数据:global_status{myXXX} = value 99 | sub fetch_mysql_data { 100 | my $result = get_mysql_info(); 101 | foreach my $row (@$result) { 102 | $global_status{ $orign_new{$row->[0]} } = $row->[1]; 103 | #say $row->[0]; # ok 104 | } 105 | 106 | } 107 | 108 | # 周期调用,更新全局变量: global_status 109 | sub refresh_status { 110 | my $now = time(); 111 | # 还没有到更新的时间点 112 | if (($now - $global_last_refresh) < $opt{refresh}) { 113 | return; 114 | } 115 | fetch_mysql_data(); 116 | $global_last_refresh = $now; 117 | return; 118 | } 119 | 120 | # 主函数 121 | sub run 122 | { 123 | netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_NO_ROOT_ACCESS, 1); 124 | my $agent = new NetSNMP::agent('Name' => 'mysql', 'AgentX' => 1); 125 | # if (!$agent) { 126 | # dolog(LOG_INFO, "agent register feature"); 127 | # } 128 | # say $?; 129 | 130 | mk_oid_table(); 131 | # 后台运行 132 | #daemonize() if !$opt{'no-daemon'}; 133 | 134 | # 注册OID 135 | $regOID = new NetSNMP::OID($opt{oid}); 136 | if ($regOID && %orign_new) { 137 | mk_oids(); 138 | } 139 | 140 | $agent->register("mysql", $regOID, \&mysql_handler); 141 | # say Dumper(keys%oids);# 如:mysqlStatus.291.0 142 | # say Dumper(\%oids); 143 | say "###########################"; 144 | say $oids{"netSnmpPlaypen.2.1.58.0"}->{'name'}; # myHandlerCommit 145 | say $oids{"netSnmpPlaypen.2.1.58.0"}->{'oid'}; # myUptimeSinceFlushStatus.0 146 | 147 | 148 | # 转换为有序的数组形式存储,便于使用 149 | # this contains a lexicographycally sorted oids array 150 | # 按 MIB 中的OID顺序排列 151 | @ordKs = sort {$a <=> $b} map {$_ = new NetSNMP::OID($_)} keys %oids; 152 | $lowestOid = $ordKs[0]; 153 | $highestOid = $ordKs[$#ordKs]; 154 | 155 | say "lowestOid:",$lowestOid; 156 | say "highestOid:",$highestOid; 157 | 158 | $running = 1; 159 | $SIG{'TERM'} = sub {$running = 0;}; 160 | $SIG{'INT'} = sub {$running = 0;}; 161 | while ($running) { 162 | refresh_status($opt{dsn}); 163 | $agent->agent_check_and_process(1); # 1 = block 使用阻塞 164 | # test 165 | # sleep(1); 166 | # $running++; 167 | } 168 | 169 | $agent->shutdown(); 170 | dolog(LOG_INFO, "agent shutdown"); 171 | } 172 | 173 | sub set_value { 174 | my ($request, $oid, $request_info) = @_; 175 | # 取key 176 | my $oidname = $oids{$oid}->{'name'}; 177 | if (!defined $oidname) { 178 | if ($oid != $regOID) { 179 | dolog(LOG_INFO, "OID $oid is not available") if ($opt{verbose}); 180 | $request->setError($request_info, SNMP_ERR_NOSUCHNAME); 181 | } 182 | return 0; 183 | } 184 | 185 | # 取值 186 | my $value = $global_status{$oidname}; 187 | if (defined $value) { 188 | dolog(LOG_DEBUG, "$oid($oidname) -> $value") if ($opt{verbose});; 189 | $request->setOID($oid); 190 | $request->setValue(ASN_OCTET_STR, "$value"); 191 | } 192 | else { 193 | dolog(LOG_DEBUG, "OID $oid has no value") if ($opt{verbose}); 194 | return 0; 195 | } 196 | return 1; 197 | } 198 | 199 | 200 | sub mysql_handler { 201 | my ($handler, $registration_info, $request_info, $requests) = @_; 202 | my ($request); 203 | 204 | #say $registration_info->getRootOID();#netSnmpPlaypen.2.1 205 | 206 | for ($request = $requests; $request; $request = $request->next()) { 207 | my $oid = $request->getOID(); 208 | my $mode = $request_info->getMode(); 209 | 210 | # say "--".$request->getValue(); 211 | # use Socket; 212 | # say "Source: ", inet_ntoa($request->getSourceIp()), "\n"; 213 | # say "Destination: ", inet_ntoa($request->getDestIp()), "\n"; 214 | 215 | dolog(LOG_DEBUG, "asking for oid $oid (mode $mode)") if ($opt{verbose}); 216 | 217 | if ($mode == MODE_GET) { 218 | set_value($request, $oid, $request_info); 219 | } 220 | elsif ($mode == MODE_GETNEXT) { 221 | if (NetSNMP::OID::compare($oid, $lowestOid) < 0) { 222 | set_value($request, $lowestOid, $request_info); 223 | } 224 | elsif (NetSNMP::OID::compare($oid, $highestOid) <= 0) #查找下一个OID 225 | { 226 | my $i = 0; 227 | my $oidToUse = undef; 228 | 229 | # 定位到下一个OID 230 | do { 231 | $oidToUse = $ordKs[$i]; 232 | $i++; 233 | } while (NetSNMP::OID::compare($oid, $oidToUse) > -1 and $i < scalar @ordKs); 234 | 235 | #获取“下一个”有效值 236 | if (defined $oidToUse) { 237 | # 对右边界OID请求GETNEXT,直接返回 238 | if (NetSNMP::OID::compare($oid, $oidToUse) == 0) { 239 | dolog(LOG_DEBUG, "GETNEXT $oid == $oidToUse, no next, returning nothing") if ($opt{verbose}); 240 | next; 241 | } 242 | dolog(LOG_DEBUG, "Next oid to $oid is $oidToUse") if ($opt{verbose}); 243 | while (!set_value($request, $oidToUse, $request_info)) { 244 | # 如果请求OID子典序的下一个OID没有值,则继续循环到一个范围内有值的OID 245 | $oidToUse = $ordKs[$i]; 246 | $i++; 247 | last if $i > scalar @ordKs; # break 248 | } 249 | } 250 | } 251 | } 252 | } 253 | dolog(LOG_DEBUG, "finished processing") if ($opt{verbose}); 254 | } 255 | 256 | # 运行 257 | run() unless caller; 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | -------------------------------------------------------------------------------- /ch9/snmpipc.c: -------------------------------------------------------------------------------- 1 | /************************************************************ 2 | * Copyright (C) GPL 3 | * FileName: snmpipc.c 4 | * Author: 张春强 5 | * Date: 2014-08 6 | * gcc -g -Wall -fPIC -shared snmpipc.c -o libsnmpipc.so 7 | ***********************************************************/ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "snmpipc.h" 17 | 18 | static int update_shm_data( int dType,T_ShmCellVal *pValue, int diretion ); 19 | 20 | // union semun { 21 | // int val; /* value for SETVAL */ 22 | // struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */ 23 | // unsigned short *array; /* array for GETALL, SETALL */ 24 | // struct seminfo *__buf; /* buffer for IPC_INFO */ 25 | // }; 26 | 27 | // 信号量ID 28 | static int s_SemId; 29 | static int s_ShmId; 30 | 31 | 32 | // 这里手工维护,结构体的映射表 33 | static T_MapTable s_tParaMapTable[] = 34 | { 35 | { .iNo = PARA_A, .iOffset = offsetof( T_ParaData, a ), .iLen = sizeof( int ) }, 36 | { .iNo = PARA_B, .iOffset = offsetof( T_ParaData, b ), .iLen = MAX_CHAR_LEN }, 37 | { .iNo = PARA_C1, .iOffset = offsetof( T_ParaData, c ), .iLen = sizeof( int ) }, 38 | { .iNo = PARA_C2, .iOffset = offsetof( T_ParaData, c ) + sizeof( int ), .iLen = sizeof( int ) }, 39 | { .iNo = PARA_C3, .iOffset = offsetof( T_ParaData, c ) + 2 * sizeof( int ), .iLen = sizeof( int ) }, 40 | }; 41 | #define PARA_NUM ( sizeof( s_tParaMapTable ) / sizeof( T_MapTable ) ) 42 | 43 | static T_MapTable s_tRealDtMapTable[] = 44 | { 45 | { .iNo = XY0X, .iOffset = offsetof( T_RealData, xy[0].x ), .iLen = sizeof( int ) }, 46 | { .iNo = XY0Y, .iOffset = offsetof( T_RealData, xy[0].y ), .iLen = sizeof( int ) }, 47 | { .iNo = XY1X, .iOffset = offsetof( T_RealData, xy[1].x ), .iLen = sizeof( int ) }, 48 | { .iNo = XY1Y, .iOffset = offsetof( T_RealData, xy[1].y ), .iLen = sizeof( int ) }, 49 | { .iNo = REALZ, .iOffset = offsetof( T_RealData, z ), .iLen = sizeof( int ) }, 50 | }; 51 | #define REALDATA_NUM ( sizeof( s_tRealDtMapTable ) / sizeof( T_MapTable ) ) 52 | 53 | static T_MapTable s_tAlarmDtMapTable[] = 54 | { 55 | { .iNo = ALARM1, .iOffset = offsetof( T_AlarmData, alarm1 ), .iLen = sizeof( int ) }, 56 | { .iNo = ALARM2, .iOffset = offsetof( T_AlarmData, alarm2 ), .iLen = MAX_CHAR_LEN }, 57 | { .iNo = ALARM_COUNTER, .iOffset = offsetof( T_AlarmData, alarmCounter ), .iLen = sizeof( int ) }, 58 | }; 59 | #define ALARMDATA_NUM ( sizeof( s_tAlarmDtMapTable ) / sizeof( T_MapTable ) ) 60 | 61 | 62 | // 数据量大小定义 63 | static int s_acMaxObjNum[SHM_TYPE_NUM] = 64 | { 65 | PARA_NUM, 66 | REALDATA_NUM, 67 | ALARMDATA_NUM, 68 | 0, 69 | }; 70 | 71 | // 共享内存大小与地址 72 | static T_ShareMem s_atShareMem[] = 73 | { 74 | { .iSize = PARA_NUM * sizeof( T_ShmCellVal ), .pShmAddr = NULL }, 75 | { .iSize = REALDATA_NUM * sizeof( int ), .pShmAddr = NULL }, 76 | { .iSize = ALARMDATA_NUM * sizeof( int ), .pShmAddr = NULL }, 77 | }; 78 | 79 | #define SHM_ARRAY_SIZE sizeof( s_atShareMem ) / sizeof( T_ShareMem ) 80 | #define SHM_CELL_SIZE sizeof( T_ShmCellVal ) 81 | 82 | static void check_file_exist( char *pName ); 83 | static int get_maxobj_num(int dType); 84 | static void update_para_data(T_ParaData* pData, int direction); 85 | static void update_realtime_data(T_RealData* pData, int direction); 86 | /*********************************************************** 87 | * Description: 返回dType数据类型中对象的数量 88 | ***********************************************************/ 89 | static int get_maxobj_num(int dType) 90 | { 91 | if( ( dType >= SHM_PARADATA) 92 | && (dType < SHM_TYPE_NUM ) 93 | ) 94 | return s_acMaxObjNum[dType]; 95 | 96 | return FAILURE; 97 | } 98 | 99 | /*********************************************************** 100 | * Description: 获取dType数据类型MAP内存的起始地址 101 | ***********************************************************/ 102 | T_MapTable* get_maptable(int dType) 103 | { 104 | T_MapTable * pMapData = NULL; 105 | if( dType == SHM_PARADATA ) 106 | { 107 | pMapData = s_tParaMapTable; 108 | 109 | }else if( dType == SHM_REALDATA ) 110 | { 111 | pMapData = s_tRealDtMapTable; 112 | }else if( dType == SHM_ALARM ) 113 | { 114 | pMapData = s_tAlarmDtMapTable; 115 | } 116 | return pMapData; 117 | } 118 | 119 | /*********************************************************** 120 | * Description: 返回拷贝的长度 121 | ***********************************************************/ 122 | static int app_memcpy( void* pValInner, void* pShmVal, int iLen, int diretion ) 123 | { 124 | if( NULL == pValInner || NULL == pShmVal || iLen <= 0 ) 125 | return 0; 126 | 127 | if( TO_SHM == diretion ) // 设置到共享内存 128 | { 129 | memcpy( pShmVal, pValInner, iLen ); 130 | } else if( FROM_SHM == diretion ) // 从共享内存取 131 | { 132 | memcpy( pValInner, pShmVal, iLen ); 133 | } else 134 | { 135 | return 0; 136 | } 137 | return iLen; 138 | } 139 | 140 | /*********************************************************** 141 | * Description: 检查文件是否存在,不存在则创建 142 | ***********************************************************/ 143 | static void check_file_exist( char *pName ) 144 | { 145 | FILE *pF; 146 | if( access( pName, F_OK ) < 0 ) 147 | { 148 | pF = fopen( pName, "w" ); 149 | if( pF ) 150 | { 151 | ///随意写个路径到该文件中 152 | fwrite( pName, strlen( pName ), 1, pF ); 153 | fclose( pF ); 154 | }else 155 | { 156 | printf( "check_file_exist: %s failed!!", pName ); 157 | } 158 | } 159 | return; 160 | } 161 | 162 | 163 | static int get_shm_size() 164 | { 165 | int i =0,j=0; 166 | // 计算共享内存总大小 167 | for( i = 0; i < SHM_ARRAY_SIZE; i++ ) 168 | j += s_atShareMem[i].iSize; 169 | return j; 170 | } 171 | 172 | static int get_shm_key() 173 | { 174 | char acFile[256] = { 0 }; 175 | int iShmKey; 176 | // 该文件用于获取共享内存的key 177 | sprintf( acFile, "%s%s", APP_DIR, SHM_CONF ); 178 | check_file_exist( acFile ); 179 | // 获得key值 180 | iShmKey = ftok( acFile, SHM_KEY_ID ); 181 | if( iShmKey == (key_t)-1 ) 182 | { 183 | printf( "get_share_memory:ftok() for shm failed!!\n" ); 184 | return FAILURE; 185 | } 186 | printf( "ftok return key = 0x%x\n", iShmKey ); 187 | return iShmKey; 188 | } 189 | 190 | static int shmget_create(int iShmKey,int iShmSize) 191 | { 192 | 193 | if( iShmKey == FAILURE|| iShmSize <=0) 194 | return FAILURE; 195 | 196 | // 创建所有用户可读写的共享内存 197 | s_ShmId = shmget( iShmKey, iShmSize, 0666 | IPC_CREAT ); 198 | if( -1 == s_ShmId ) 199 | { 200 | printf( "get_share_memory:shmget() failed!!\n" ); 201 | return FAILURE; 202 | } 203 | return SUCCESS; 204 | } 205 | 206 | static int shmget_get(int iShmKey,int iShmSize) 207 | { 208 | 209 | if( iShmKey == FAILURE|| iShmSize <=0) 210 | return FAILURE; 211 | 212 | // 获取共享内存 213 | s_ShmId = shmget( iShmKey, iShmSize, 0666 ); 214 | if( -1 == s_ShmId ) 215 | { 216 | printf( "get_share_memory:shmget() failed!!\n" ); 217 | return FAILURE; 218 | } 219 | return SUCCESS; 220 | } 221 | 222 | static void allocate_shm( void*pShmAddr ) 223 | { 224 | int i =0; 225 | if(NULL == pShmAddr) 226 | { 227 | printf("NULL ADDRESS!!\n"); 228 | return; 229 | } 230 | // 为各类数据分配共享内存起始地址 231 | for( i = 0; i < SHM_ARRAY_SIZE; i++ ) 232 | { 233 | s_atShareMem[i].pShmAddr = pShmAddr; 234 | printf( "shm adress:0x%x\n", (unsigned int )s_atShareMem[i].pShmAddr ); 235 | pShmAddr = (void*)( (int)pShmAddr + s_atShareMem[i].iSize ); 236 | } 237 | return; 238 | } 239 | 240 | /*********************************************************** 241 | * Description: 获取共享内存的ID 242 | ***********************************************************/ 243 | static int get_shmid( ) 244 | { 245 | return s_ShmId; 246 | } 247 | 248 | /*********************************************************** 249 | * Description: 获取信号量的ID 250 | ***********************************************************/ 251 | static int get_semid( ) 252 | { 253 | return s_SemId; 254 | } 255 | 256 | void *shm_attach( ) 257 | { 258 | void *pShmAddr = NULL; 259 | // 最后一个参数为0 表示可读写 260 | pShmAddr = shmat( get_shmid(), NULL, 0 ); 261 | if( NULL == pShmAddr ) 262 | { 263 | del_shm(); 264 | printf( "main:shmat() failed!!\n" ); 265 | return NULL; 266 | } 267 | return pShmAddr; 268 | } 269 | /*********************************************************** 270 | * Description: 271 | bIsMaster为真创建共享内存,否则获取共享内存的ID; 272 | 作为公共库,该函数只要主业务进程调用一次就OK了, 273 | 传入参数bIsMaster为1,SNMP代理可不用调用该接口; 274 | ***********************************************************/ 275 | static int init_share_memory( BOOLEAN bIsMaster ) 276 | { 277 | void *pShmAddr = NULL; 278 | 279 | if( bIsMaster ) 280 | { 281 | // 创建所有用户可读写的共享内存 282 | if(FAILURE == shmget_create(get_shm_key(),get_shm_size()) ) 283 | return FAILURE; 284 | }else 285 | { 286 | // 获取共享内存 287 | if(FAILURE == shmget_get(get_shm_key(),get_shm_size()) ) 288 | return FAILURE; 289 | } 290 | printf( "shm id = %d \n", get_shmid() ); 291 | 292 | pShmAddr = shm_attach(); 293 | if(NULL == pShmAddr) return FAILURE; 294 | 295 | if( bIsMaster ) //共享内存显示初始化,先启动! 296 | memset( pShmAddr, 0x00, get_shm_size() ); 297 | 298 | // 为各类数据分配共享内存起始地址 299 | allocate_shm(pShmAddr); 300 | 301 | return get_shmid(); 302 | } 303 | 304 | /*********************************************************** 305 | * Description: 获取共享内存地址 306 | ***********************************************************/ 307 | static void * get_shm_addr( int dtype ) 308 | { 309 | if( 0 <= dtype && dtype < SHM_TYPE_NUM ) 310 | return s_atShareMem[dtype].pShmAddr; 311 | 312 | return NULL; 313 | } 314 | 315 | 316 | static int get_sem_key() 317 | { 318 | char acFile[256] = { 0 }; 319 | int iSemKey =-1; 320 | // 该文件用于获取共享内存的key 321 | sprintf( acFile, "%s%s", APP_DIR, SEM_CONF ); 322 | check_file_exist( acFile ); 323 | iSemKey = ftok( acFile, SEM_KEY_ID ); 324 | 325 | if( iSemKey == (key_t)-1 ) 326 | { 327 | printf( "get_sem_key:ftok() for sem failed!!\n" ); 328 | return FAILURE; 329 | } 330 | printf( "ftok return key = 0x%x\n", iSemKey ); 331 | return iSemKey; 332 | } 333 | 334 | static int semget_create( int iSemKey ) 335 | { 336 | int i =0; 337 | if( iSemKey == FAILURE ) 338 | return FAILURE; 339 | 340 | // 创建所有用户可读写的信号量 341 | s_SemId = semget( iSemKey, SEM_NUM, 0666 | IPC_CREAT ); 342 | if( -1 == s_SemId ) 343 | { 344 | printf( "semget_create:semget() failed!!\n" ); 345 | return FAILURE; 346 | } 347 | // 初始化信号量: 348 | //使用for循环和SETVAL单独设置每个信号量值为1——可获得 349 | for( i = 0; i < SEM_NUM; i++ ) 350 | { 351 | if( semctl( s_SemId, i, SETVAL, 1 ) < 0 ) 352 | { 353 | return FAILURE; 354 | } 355 | } 356 | return s_SemId; 357 | } 358 | 359 | static int semget_get( int iSemKey ) 360 | { 361 | 362 | if( iSemKey == FAILURE ) 363 | return FAILURE; 364 | 365 | s_SemId = semget( iSemKey, SEM_NUM, 0666 ); 366 | if( -1 == s_SemId ) 367 | { 368 | printf( "semget_get:semget() failed!!\n" ); 369 | return FAILURE; 370 | } 371 | return s_SemId; 372 | } 373 | 374 | 375 | /*********************************************************** 376 | * Description: 创建信号量 377 | bIsMaster 为真创建,否则获取 378 | ***********************************************************/ 379 | static int create_semaphore( BOOLEAN bIsMaster ) 380 | { 381 | if( bIsMaster ) 382 | // 创建所有用户可读写的信号量 383 | semget_create( get_sem_key() ); 384 | else 385 | semget_get( get_sem_key()); 386 | 387 | printf( "s_SemId=%d \n", get_semid() ); 388 | return get_semid(); 389 | } 390 | 391 | /*********************************************************** 392 | * Description: 删除共享内存 393 | ***********************************************************/ 394 | int del_shm( ) 395 | { 396 | int rc; 397 | rc = shmctl( s_ShmId, IPC_RMID, NULL ); 398 | if( FAILURE == rc ) 399 | { 400 | printf( "del_shm: shmctl() failed!!\n" ); 401 | return FAILURE; 402 | } 403 | return SUCCESS; 404 | } 405 | 406 | /*********************************************************** 407 | * Description: 对单个信号量V操作,释放资源; 408 | ***********************************************************/ 409 | static int unlock_sem( int slNo ) 410 | { 411 | struct sembuf tSem; 412 | tSem.sem_num = slNo; 413 | tSem.sem_op = 1; 414 | tSem.sem_flg = SEM_UNDO; 415 | return 416 | semop( s_SemId, &tSem, 1 ); 417 | } 418 | 419 | /*********************************************************** 420 | * Description: 421 | 对单个信号量P操作,取得资源 422 | 使用SEM_UNDO选项,防止该进程异常退出时可能的死锁; 423 | ***********************************************************/ 424 | static int lock_sem( int slNo ) 425 | { 426 | struct sembuf tSem; 427 | tSem.sem_num = slNo; 428 | tSem.sem_op = -1; 429 | tSem.sem_flg = SEM_UNDO; 430 | return 431 | semop( s_SemId, &tSem, 1 ); 432 | } 433 | 434 | /*********************************************************** 435 | * Description: 获取信号量的值 436 | ***********************************************************/ 437 | static int get_sem( int slNo ) 438 | { 439 | return 440 | semctl( s_SemId, 0, GETVAL ); 441 | } 442 | 443 | /*********************************************************** 444 | * Description: 删除信号量 445 | ***********************************************************/ 446 | int del_sem( void ) 447 | { 448 | int rc; 449 | rc = semctl( s_SemId, 0, IPC_RMID ); 450 | if( rc == -1 ) 451 | { 452 | perror( "del_sem:semctl() remove id failed!!\n" ); 453 | return FAILURE; 454 | } 455 | return SUCCESS; 456 | } 457 | 458 | static void set_shmcellval(T_ShmCellVal* shmVal,int no,int ll) 459 | { 460 | if(NULL != shmVal) 461 | { 462 | bzero( (void*)shmVal, (size_t)sizeof( T_ShmCellVal ) ); 463 | shmVal->iNo = no; 464 | shmVal->iLen = ll; 465 | } 466 | return; 467 | } 468 | 469 | /*********************************************************** 470 | * Description: 471 | SNMP代理使用的数据更新接口; 472 | 更新数据,返回更新的字节数; 473 | 实际上,这些初始化的工作都可以不用代码来实现, 474 | 比如在真实的项目中,我们往往会定义所有需要的监控项。 475 | 定义的内容无非就是各个监控量的属性, 476 | 如数据类型,字节长度,读写权限,数组数量,缺省值等等。 477 | 这份定义文件我们可以称之为系统监控对象的数据字典。 478 | 我们只要解析该数据字典生成一份与代码中结构体一致的二进制的文件, 479 | 每次初始化时只要直接读取该文件的内容到共享内存段,即可完成系统的初始化的工作。 480 | ***********************************************************/ 481 | static int updata_cellvalue( int dType, int no, int ll, void* pV, int diretion ) 482 | { 483 | T_ShmCellVal shmVal; 484 | int ret = 0; 485 | if( no < 0 486 | || ll < 0 487 | || NULL == pV 488 | || ( dType < SHM_PARADATA || dType >= SHM_TYPE_NUM ) 489 | ) 490 | { 491 | printf( "updata_cellvalue failed!!\n" ); 492 | return 0; 493 | } 494 | 495 | set_shmcellval(&shmVal,no,ll); 496 | 497 | // 设置或获取 498 | // 设置时: pV -> shmVal.uValue ,获取时无需操作 499 | if( TO_SHM == diretion ) 500 | app_memcpy( pV, &shmVal.uValue, ll, diretion ); 501 | 502 | ret = update_shm_data( dType, &shmVal, diretion ); 503 | 504 | // 获取时: shmVal.uValue -> pv,设置时无需操作 505 | if( (FROM_SHM == diretion) && (0 < ret) ) 506 | ret = app_memcpy( pV, &shmVal.uValue, ret, diretion ); 507 | 508 | return ret; 509 | } 510 | 511 | 512 | static void* get_update_addr(int dType,const T_ShmCellVal *pValue) 513 | { 514 | 515 | if( NULL == pValue ) return NULL; 516 | 517 | char *pShmAddr = (char*)get_shm_addr( dType ); 518 | T_MapTable *pMapTable= get_maptable( dType ); 519 | 520 | if(NULL != pMapTable) 521 | { // 取指定位置的单元地址 522 | pShmAddr += pMapTable[pValue->iNo].iOffset; 523 | return (void*)pShmAddr; 524 | }else 525 | return NULL; 526 | } 527 | 528 | static int get_update_len(int dType,const T_ShmCellVal *pValue) 529 | { 530 | if( NULL == pValue ) return 0; 531 | 532 | T_MapTable *pMapTable= get_maptable( dType ); 533 | 534 | if(NULL != pMapTable) 535 | return MIN( pMapTable[pValue->iNo].iLen, pValue->iLen ); 536 | else 537 | return 0; 538 | } 539 | 540 | /*********************************************************** 541 | * Description: 542 | SNMP代理使用的数据更新接口; 543 | pValue 传入的是T_ShmCellVal 指针,作为输入输出; 544 | 返回拷贝的长度; 545 | ***********************************************************/ 546 | static int update_shm_data( int dType, T_ShmCellVal *pValue, int diretion ) 547 | { 548 | 549 | void * pShmAddr = get_update_addr(dType,pValue); 550 | int iLen = get_update_len(dType,pValue); 551 | 552 | if( NULL == pShmAddr ||iLen <=0 ) return 0; 553 | 554 | lock_sem( dType ); 555 | app_memcpy( &pValue->uValue, pShmAddr, iLen, diretion ); 556 | unlock_sem( dType ); 557 | 558 | return iLen; 559 | } 560 | 561 | 562 | /* 563 | 更新所有数据: 564 | 下面硬编码了只有几个数据的参数结构, 565 | 实际中,一个系统的参数远远不只这些,如果还使用这种方式,肯定不是一个好的解决方案。 566 | 一般情况下,对于多个数据的处理方式最简洁的编码形式是使用循环。 567 | 而使用循环必然要求对所有的数据类型的处理方式都一样。 568 | 依照这种思路,常规的编码方式是定义通用的结构体和增加额外的可供循环统一处理的信息,如唯一标识的方法。 569 | 对于数据的处理较为常规的编码技巧是将对象分为:数值、属性、标识; 570 | 采用这种分层的思想,所有的数据都抽象为统一的处理方法了! 571 | 这里就不详述了,“废话”似乎够多了! 572 | */ 573 | 574 | /*********************************************************** 575 | * Description: 更新通用结构体与共享内存的数据 576 | ***********************************************************/ 577 | static void _update_data(void* pData, int dType,int direction) 578 | { 579 | char *pAddr = NULL; 580 | int i = 0; 581 | T_MapTable *pMap = get_maptable( dType ); 582 | if( NULL == pMap || NULL == pData ) return; 583 | 584 | for(i = 0; i < get_maxobj_num(dType); i++ ) 585 | { 586 | pAddr = (char *)pData; 587 | updata_cellvalue( dType,i,pMap[i].iLen, 588 | pAddr+pMap[i].iOffset, direction); 589 | } 590 | 591 | return; 592 | } 593 | 594 | /*********************************************************** 595 | * Description: 参数结构体变量与共享内存数据更新 596 | ***********************************************************/ 597 | static void update_para_data(T_ParaData* pData, int direction) 598 | { 599 | return 600 | _update_data(pData,SHM_PARADATA,direction); 601 | 602 | } 603 | 604 | /*********************************************************** 605 | * Description: 实时数据结构体变量与共享内存数据更新 606 | ***********************************************************/ 607 | static void update_realtime_data(T_RealData* pData, int direction) 608 | { 609 | 610 | void * pShmVal = get_shm_addr( SHM_REALDATA ); 611 | if( NULL == pShmVal || NULL == pData ) return; 612 | 613 | lock_sem( SHM_REALDATA ); 614 | app_memcpy( pData, pShmVal, sizeof(T_RealData),direction); 615 | unlock_sem( SHM_REALDATA ); 616 | 617 | return; 618 | } 619 | 620 | /*********************************************************** 621 | * Description: 告警数据结构体变量与共享内存数据更新 622 | ***********************************************************/ 623 | static void update_alarm_data(T_AlarmData* pData, int direction) 624 | { 625 | return 626 | _update_data(pData,SHM_ALARM,direction); 627 | } 628 | 629 | 630 | /*********************************************************** 631 | * Description: 业务进程使用: 结构体变量与共享内存数据更新; 632 | pStrVal,为业务进程中结构体变量; 633 | dir,取值为FROM_SHM和TO_SHM,分别表示读写共享内存; 634 | ***********************************************************/ 635 | static int update_data(void* pStrVal, int dType, int dir) 636 | { 637 | if( NULL == pStrVal ) return FAILURE; 638 | 639 | if( SHM_PARADATA == dType) 640 | update_para_data( pStrVal, dir ); 641 | else if( SHM_REALDATA == dType ) 642 | update_realtime_data(pStrVal, dir); 643 | else if( SHM_ALARM== dType ) 644 | update_alarm_data(pStrVal, dir); 645 | else 646 | return FAILURE; 647 | 648 | return SUCCESS; 649 | } 650 | 651 | /*********************************************************** 652 | * Description: 业务进程使用: 653 | 从共享内存中读数据更新到结构体 654 | pStrVal,为业务进程中结构体变量指针; 655 | dType:数据类型 656 | ***********************************************************/ 657 | int app_get_data(void* pStrVal, int dType) 658 | { 659 | return 660 | update_data(pStrVal, dType,FROM_SHM); 661 | } 662 | 663 | /*********************************************************** 664 | * Description: 业务进程使用: 665 | 从结构体写到共享内存中 666 | pStrVal,为业务进程中结构体变量指针; 667 | dType:数据类型 668 | ***********************************************************/ 669 | int app_set_data(void* pStrVal, int dType) 670 | { 671 | return 672 | update_data(pStrVal, dType,TO_SHM); 673 | } 674 | 675 | 676 | /*********************************************************** 677 | * Description: snmp进程使用: 678 | 从共享内存中读数据到pV 679 | dType:数据类型 680 | no:序号 681 | ll:字节长度 682 | pV:变量地址 683 | ***********************************************************/ 684 | int snmp_get_data( int dType, int no, int ll, void* pV ) 685 | { 686 | return 687 | updata_cellvalue(dType,no,ll,pV,FROM_SHM); 688 | } 689 | 690 | /*********************************************************** 691 | * Description: snmp进程使用: 692 | 将pV内容写入到共享内存中 693 | dType:数据类型 694 | no:序号 695 | ll:字节长度 696 | pV:变量地址 697 | ***********************************************************/ 698 | int snmp_set_data( int dType, int no, int ll, void* pV ) 699 | { 700 | return 701 | updata_cellvalue(dType,no,ll,pV,TO_SHM); 702 | } 703 | 704 | 705 | /*********************************************************** 706 | * Description:共享内存和信号量初始化 707 | isMaster指示是否为主业务进程,该进程负责创建和初始化 708 | ***********************************************************/ 709 | static void init_shm_sem(BOOLEAN isMaster) 710 | { 711 | if( FAILURE == init_share_memory( isMaster ) ) 712 | exit (-1); 713 | 714 | if( FAILURE == create_semaphore( isMaster ) ) 715 | exit (-1); 716 | } 717 | 718 | 719 | /*********************************************************** 720 | * Description:主进程 调用初始化共享内存和信号量 721 | ***********************************************************/ 722 | 723 | void init_shm_sem_master() 724 | { 725 | init_shm_sem(1); 726 | } 727 | 728 | /*********************************************************** 729 | * Description:非主进程 调用初始化共享内存和信号量 730 | ***********************************************************/ 731 | void init_shm_sem_slave() 732 | { 733 | init_shm_sem(0); 734 | } 735 | 736 | -------------------------------------------------------------------------------- /ch7/httpd.conf: -------------------------------------------------------------------------------- 1 | # 2 | # This is the main Apache server configuration file. It contains the 3 | # configuration directives that give the server its instructions. 4 | # See for detailed information. 5 | # In particular, see 6 | # 7 | # for a discussion of each configuration directive. 8 | # 9 | # 10 | # Do NOT simply read the instructions in here without understanding 11 | # what they do. They're here only as hints or reminders. If you are unsure 12 | # consult the online docs. You have been warned. 13 | # 14 | # The configuration directives are grouped into three basic sections: 15 | # 1. Directives that control the operation of the Apache server process as a 16 | # whole (the 'global environment'). 17 | # 2. Directives that define the parameters of the 'main' or 'default' server, 18 | # which responds to requests that aren't handled by a virtual host. 19 | # These directives also provide default values for the settings 20 | # of all virtual hosts. 21 | # 3. Settings for virtual hosts, which allow Web requests to be sent to 22 | # different IP addresses or hostnames and have them handled by the 23 | # same Apache server process. 24 | # 25 | # Configuration and logfile names: If the filenames you specify for many 26 | # of the server's control files begin with "/" (or "drive:/" for Win32), the 27 | # server will use that explicit path. If the filenames do *not* begin 28 | # with "/", the value of ServerRoot is prepended -- so "logs/foo.log" 29 | # with ServerRoot set to "/etc/httpd" will be interpreted by the 30 | # server as "/etc/httpd/logs/foo.log". 31 | # 32 | 33 | ### Section 1: Global Environment 34 | # 35 | # The directives in this section affect the overall operation of Apache, 36 | # such as the number of concurrent requests it can handle or where it 37 | # can find its configuration files. 38 | # 39 | 40 | # 41 | # Don't give away too much information about all the subcomponents 42 | # we are running. Comment out this line if you don't mind remote sites 43 | # finding out what major optional modules you are running 44 | ServerTokens OS 45 | 46 | # 47 | # ServerRoot: The top of the directory tree under which the server's 48 | # configuration, error, and log files are kept. 49 | # 50 | # NOTE! If you intend to place this on an NFS (or otherwise network) 51 | # mounted filesystem then please read the LockFile documentation 52 | # (available at ); 53 | # you will save yourself a lot of trouble. 54 | # 55 | # Do NOT add a slash at the end of the directory path. 56 | # 57 | ServerRoot "/etc/httpd" 58 | 59 | # 60 | # PidFile: The file in which the server should record its process 61 | # identification number when it starts. Note the PIDFILE variable in 62 | # /etc/sysconfig/httpd must be set appropriately if this location is 63 | # changed. 64 | # 65 | PidFile run/httpd.pid 66 | 67 | # 68 | # Timeout: The number of seconds before receives and sends time out. 69 | # 70 | Timeout 60 71 | 72 | # 73 | # KeepAlive: Whether or not to allow persistent connections (more than 74 | # one request per connection). Set to "Off" to deactivate. 75 | # 76 | KeepAlive Off 77 | 78 | # 79 | # MaxKeepAliveRequests: The maximum number of requests to allow 80 | # during a persistent connection. Set to 0 to allow an unlimited amount. 81 | # We recommend you leave this number high, for maximum performance. 82 | # 83 | MaxKeepAliveRequests 100 84 | 85 | # 86 | # KeepAliveTimeout: Number of seconds to wait for the next request from the 87 | # same client on the same connection. 88 | # 89 | KeepAliveTimeout 15 90 | 91 | ## 92 | ## Server-Pool Size Regulation (MPM specific) 93 | ## 94 | 95 | # prefork MPM 96 | # StartServers: number of server processes to start 97 | # MinSpareServers: minimum number of server processes which are kept spare 98 | # MaxSpareServers: maximum number of server processes which are kept spare 99 | # ServerLimit: maximum value for MaxClients for the lifetime of the server 100 | # MaxClients: maximum number of server processes allowed to start 101 | # MaxRequestsPerChild: maximum number of requests a server process serves 102 | 103 | StartServers 8 104 | MinSpareServers 5 105 | MaxSpareServers 20 106 | ServerLimit 256 107 | MaxClients 256 108 | MaxRequestsPerChild 4000 109 | 110 | 111 | # worker MPM 112 | # StartServers: initial number of server processes to start 113 | # MaxClients: maximum number of simultaneous client connections 114 | # MinSpareThreads: minimum number of worker threads which are kept spare 115 | # MaxSpareThreads: maximum number of worker threads which are kept spare 116 | # ThreadsPerChild: constant number of worker threads in each server process 117 | # MaxRequestsPerChild: maximum number of requests a server process serves 118 | 119 | StartServers 4 120 | MaxClients 300 121 | MinSpareThreads 25 122 | MaxSpareThreads 75 123 | ThreadsPerChild 25 124 | MaxRequestsPerChild 0 125 | 126 | 127 | # 128 | # Listen: Allows you to bind Apache to specific IP addresses and/or 129 | # ports, in addition to the default. See also the 130 | # directive. 131 | # 132 | # Change this to Listen on specific IP addresses as shown below to 133 | # prevent Apache from glomming onto all bound IP addresses (0.0.0.0) 134 | # 135 | #Listen 12.34.56.78:80 136 | Listen 80 137 | 138 | # 139 | # Dynamic Shared Object (DSO) Support 140 | # 141 | # To be able to use the functionality of a module which was built as a DSO you 142 | # have to place corresponding `LoadModule' lines at this location so the 143 | # directives contained in it are actually available _before_ they are used. 144 | # Statically compiled modules (those listed by `httpd -l') do not need 145 | # to be loaded here. 146 | # 147 | # Example: 148 | # LoadModule foo_module modules/mod_foo.so 149 | # 150 | LoadModule auth_basic_module modules/mod_auth_basic.so 151 | LoadModule auth_digest_module modules/mod_auth_digest.so 152 | LoadModule authn_file_module modules/mod_authn_file.so 153 | LoadModule authn_alias_module modules/mod_authn_alias.so 154 | LoadModule authn_anon_module modules/mod_authn_anon.so 155 | LoadModule authn_dbm_module modules/mod_authn_dbm.so 156 | LoadModule authn_default_module modules/mod_authn_default.so 157 | LoadModule authz_host_module modules/mod_authz_host.so 158 | LoadModule authz_user_module modules/mod_authz_user.so 159 | LoadModule authz_owner_module modules/mod_authz_owner.so 160 | LoadModule authz_groupfile_module modules/mod_authz_groupfile.so 161 | LoadModule authz_dbm_module modules/mod_authz_dbm.so 162 | LoadModule authz_default_module modules/mod_authz_default.so 163 | LoadModule ldap_module modules/mod_ldap.so 164 | LoadModule authnz_ldap_module modules/mod_authnz_ldap.so 165 | LoadModule include_module modules/mod_include.so 166 | LoadModule log_config_module modules/mod_log_config.so 167 | LoadModule logio_module modules/mod_logio.so 168 | LoadModule env_module modules/mod_env.so 169 | LoadModule ext_filter_module modules/mod_ext_filter.so 170 | LoadModule mime_magic_module modules/mod_mime_magic.so 171 | LoadModule expires_module modules/mod_expires.so 172 | LoadModule deflate_module modules/mod_deflate.so 173 | LoadModule headers_module modules/mod_headers.so 174 | LoadModule usertrack_module modules/mod_usertrack.so 175 | LoadModule setenvif_module modules/mod_setenvif.so 176 | LoadModule mime_module modules/mod_mime.so 177 | LoadModule dav_module modules/mod_dav.so 178 | LoadModule status_module modules/mod_status.so 179 | LoadModule autoindex_module modules/mod_autoindex.so 180 | LoadModule info_module modules/mod_info.so 181 | LoadModule dav_fs_module modules/mod_dav_fs.so 182 | LoadModule vhost_alias_module modules/mod_vhost_alias.so 183 | LoadModule negotiation_module modules/mod_negotiation.so 184 | LoadModule dir_module modules/mod_dir.so 185 | LoadModule actions_module modules/mod_actions.so 186 | LoadModule speling_module modules/mod_speling.so 187 | LoadModule userdir_module modules/mod_userdir.so 188 | LoadModule alias_module modules/mod_alias.so 189 | LoadModule substitute_module modules/mod_substitute.so 190 | LoadModule rewrite_module modules/mod_rewrite.so 191 | LoadModule proxy_module modules/mod_proxy.so 192 | LoadModule proxy_balancer_module modules/mod_proxy_balancer.so 193 | LoadModule proxy_ftp_module modules/mod_proxy_ftp.so 194 | LoadModule proxy_http_module modules/mod_proxy_http.so 195 | LoadModule proxy_ajp_module modules/mod_proxy_ajp.so 196 | LoadModule proxy_connect_module modules/mod_proxy_connect.so 197 | LoadModule cache_module modules/mod_cache.so 198 | LoadModule suexec_module modules/mod_suexec.so 199 | LoadModule disk_cache_module modules/mod_disk_cache.so 200 | LoadModule cgi_module modules/mod_cgi.so 201 | LoadModule version_module modules/mod_version.so 202 | 203 | # 204 | # The following modules are not loaded by default: 205 | # 206 | #LoadModule asis_module modules/mod_asis.so 207 | #LoadModule authn_dbd_module modules/mod_authn_dbd.so 208 | #LoadModule cern_meta_module modules/mod_cern_meta.so 209 | #LoadModule cgid_module modules/mod_cgid.so 210 | #LoadModule dbd_module modules/mod_dbd.so 211 | #LoadModule dumpio_module modules/mod_dumpio.so 212 | #LoadModule filter_module modules/mod_filter.so 213 | #LoadModule ident_module modules/mod_ident.so 214 | #LoadModule log_forensic_module modules/mod_log_forensic.so 215 | #LoadModule unique_id_module modules/mod_unique_id.so 216 | # 217 | 218 | # 219 | # Load config files from the config directory "/etc/httpd/conf.d". 220 | # 221 | Include conf.d/*.conf 222 | 223 | # 224 | # ExtendedStatus controls whether Apache will generate "full" status 225 | # information (ExtendedStatus On) or just basic information (ExtendedStatus 226 | # Off) when the "server-status" handler is called. The default is Off. 227 | # 228 | #ExtendedStatus On 229 | 230 | # 231 | # If you wish httpd to run as a different user or group, you must run 232 | # httpd as root initially and it will switch. 233 | # 234 | # User/Group: The name (or #number) of the user/group to run httpd as. 235 | # . On SCO (ODT 3) use "User nouser" and "Group nogroup". 236 | # . On HPUX you may not be able to use shared memory as nobody, and the 237 | # suggested workaround is to create a user www and use that user. 238 | # NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET) 239 | # when the value of (unsigned)Group is above 60000; 240 | # don't use Group #-1 on these systems! 241 | # 242 | User cactiuser 243 | #User root 244 | Group apache 245 | #Group root 246 | 247 | ### Section 2: 'Main' server configuration 248 | # 249 | # The directives in this section set up the values used by the 'main' 250 | # server, which responds to any requests that aren't handled by a 251 | # definition. These values also provide defaults for 252 | # any containers you may define later in the file. 253 | # 254 | # All of these directives may appear inside containers, 255 | # in which case these default settings will be overridden for the 256 | # virtual host being defined. 257 | # 258 | 259 | # 260 | # ServerAdmin: Your address, where problems with the server should be 261 | # e-mailed. This address appears on some server-generated pages, such 262 | # as error documents. e.g. admin@your-domain.com 263 | # 264 | ServerAdmin root@localhost 265 | 266 | # 267 | # ServerName gives the name and port that the server uses to identify itself. 268 | # This can often be determined automatically, but we recommend you specify 269 | # it explicitly to prevent problems during startup. 270 | # 271 | # If this is not set to valid DNS name for your host, server-generated 272 | # redirections will not work. See also the UseCanonicalName directive. 273 | # 274 | # If your host doesn't have a registered DNS name, enter its IP address here. 275 | # You will have to access it by its address anyway, and this will make 276 | # redirections work in a sensible way. 277 | # 278 | #ServerName www.example.com:80 279 | ServerName 127.0.0.1:80 280 | # 281 | # UseCanonicalName: Determines how Apache constructs self-referencing 282 | # URLs and the SERVER_NAME and SERVER_PORT variables. 283 | # When set "Off", Apache will use the Hostname and Port supplied 284 | # by the client. When set "On", Apache will use the value of the 285 | # ServerName directive. 286 | # 287 | UseCanonicalName Off 288 | 289 | # 290 | # DocumentRoot: The directory out of which you will serve your 291 | # documents. By default, all requests are taken from this directory, but 292 | # symbolic links and aliases may be used to point to other locations. 293 | # 294 | #DocumentRoot "/var/www/html" 295 | DocumentRoot "/var/www/html/cacti" 296 | 297 | # 298 | # Each directory to which Apache has access can be configured with respect 299 | # to which services and features are allowed and/or disabled in that 300 | # directory (and its subdirectories). 301 | # 302 | # First, we configure the "default" to be a very restrictive set of 303 | # features. 304 | # 305 | 306 | Options FollowSymLinks 307 | AllowOverride None 308 | 309 | 310 | # 311 | # Note that from this point forward you must specifically allow 312 | # particular features to be enabled - so if something's not working as 313 | # you might expect, make sure that you have specifically enabled it 314 | # below. 315 | # 316 | 317 | # 318 | # This should be changed to whatever you set DocumentRoot to. 319 | # 320 | # 321 | 322 | 323 | # 324 | # Possible values for the Options directive are "None", "All", 325 | # or any combination of: 326 | # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews 327 | # 328 | # Note that "MultiViews" must be named *explicitly* --- "Options All" 329 | # doesn't give it to you. 330 | # 331 | # The Options directive is both complicated and important. Please see 332 | # http://httpd.apache.org/docs/2.2/mod/core.html#options 333 | # for more information. 334 | # 335 | Options Indexes FollowSymLinks 336 | 337 | # 338 | # AllowOverride controls what directives may be placed in .htaccess files. 339 | # It can be "All", "None", or any combination of the keywords: 340 | # Options FileInfo AuthConfig Limit 341 | # 342 | AllowOverride None 343 | 344 | # 345 | # Controls who can get stuff from this server. 346 | # 347 | Order allow,deny 348 | Allow from all 349 | # Allow from 127.0.0.1 350 | # Allow from ::1 351 | # Require user cactiuser 352 | 353 | 354 | # 355 | # UserDir: The name of the directory that is appended onto a user's home 356 | # directory if a ~user request is received. 357 | # 358 | # The path to the end user account 'public_html' directory must be 359 | # accessible to the webserver userid. This usually means that ~userid 360 | # must have permissions of 711, ~userid/public_html must have permissions 361 | # of 755, and documents contained therein must be world-readable. 362 | # Otherwise, the client will only receive a "403 Forbidden" message. 363 | # 364 | # See also: http://httpd.apache.org/docs/misc/FAQ.html#forbidden 365 | # 366 | 367 | # 368 | # UserDir is disabled by default since it can confirm the presence 369 | # of a username on the system (depending on home directory 370 | # permissions). 371 | # 372 | UserDir disabled 373 | 374 | # 375 | # To enable requests to /~user/ to serve the user's public_html 376 | # directory, remove the "UserDir disabled" line above, and uncomment 377 | # the following line instead: 378 | # 379 | #UserDir public_html 380 | 381 | 382 | 383 | # 384 | # Control access to UserDir directories. The following is an example 385 | # for a site where these directories are restricted to read-only. 386 | # 387 | # 388 | # AllowOverride FileInfo AuthConfig Limit 389 | # Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec 390 | # 391 | # Order allow,deny 392 | # Allow from all 393 | # 394 | # 395 | # Order deny,allow 396 | # Deny from all 397 | # 398 | # 399 | 400 | # 401 | # DirectoryIndex: sets the file that Apache will serve if a directory 402 | # is requested. 403 | # 404 | # The index.html.var file (a type-map) is used to deliver content- 405 | # negotiated documents. The MultiViews Option can be used for the 406 | # same purpose, but it is much slower. 407 | # 408 | DirectoryIndex index.php index.html index.html.var 409 | 410 | # 411 | # AccessFileName: The name of the file to look for in each directory 412 | # for additional configuration directives. See also the AllowOverride 413 | # directive. 414 | # 415 | AccessFileName .htaccess 416 | 417 | # 418 | # The following lines prevent .htaccess and .htpasswd files from being 419 | # viewed by Web clients. 420 | # 421 | 422 | Order allow,deny 423 | Deny from all 424 | Satisfy All 425 | 426 | 427 | # 428 | # TypesConfig describes where the mime.types file (or equivalent) is 429 | # to be found. 430 | # 431 | TypesConfig /etc/mime.types 432 | 433 | # 434 | # DefaultType is the default MIME type the server will use for a document 435 | # if it cannot otherwise determine one, such as from filename extensions. 436 | # If your server contains mostly text or HTML documents, "text/plain" is 437 | # a good value. If most of your content is binary, such as applications 438 | # or images, you may want to use "application/octet-stream" instead to 439 | # keep browsers from trying to display binary files as though they are 440 | # text. 441 | # 442 | DefaultType text/plain 443 | 444 | # 445 | # The mod_mime_magic module allows the server to use various hints from the 446 | # contents of the file itself to determine its type. The MIMEMagicFile 447 | # directive tells the module where the hint definitions are located. 448 | # 449 | 450 | # MIMEMagicFile /usr/share/magic.mime 451 | MIMEMagicFile conf/magic 452 | 453 | 454 | # 455 | # HostnameLookups: Log the names of clients or just their IP addresses 456 | # e.g., www.apache.org (on) or 204.62.129.132 (off). 457 | # The default is off because it'd be overall better for the net if people 458 | # had to knowingly turn this feature on, since enabling it means that 459 | # each client request will result in AT LEAST one lookup request to the 460 | # nameserver. 461 | # 462 | HostnameLookups Off 463 | 464 | # 465 | # EnableMMAP: Control whether memory-mapping is used to deliver 466 | # files (assuming that the underlying OS supports it). 467 | # The default is on; turn this off if you serve from NFS-mounted 468 | # filesystems. On some systems, turning it off (regardless of 469 | # filesystem) can improve performance; for details, please see 470 | # http://httpd.apache.org/docs/2.2/mod/core.html#enablemmap 471 | # 472 | #EnableMMAP off 473 | 474 | # 475 | # EnableSendfile: Control whether the sendfile kernel support is 476 | # used to deliver files (assuming that the OS supports it). 477 | # The default is on; turn this off if you serve from NFS-mounted 478 | # filesystems. Please see 479 | # http://httpd.apache.org/docs/2.2/mod/core.html#enablesendfile 480 | # 481 | #EnableSendfile off 482 | 483 | # 484 | # ErrorLog: The location of the error log file. 485 | # If you do not specify an ErrorLog directive within a 486 | # container, error messages relating to that virtual host will be 487 | # logged here. If you *do* define an error logfile for a 488 | # container, that host's errors will be logged there and not here. 489 | # 490 | ErrorLog logs/error_log 491 | 492 | # 493 | # LogLevel: Control the number of messages logged to the error_log. 494 | # Possible values include: debug, info, notice, warn, error, crit, 495 | # alert, emerg. 496 | # 497 | LogLevel warn 498 | 499 | # 500 | # The following directives define some format nicknames for use with 501 | # a CustomLog directive (see below). 502 | # 503 | LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined 504 | LogFormat "%h %l %u %t \"%r\" %>s %b" common 505 | LogFormat "%{Referer}i -> %U" referer 506 | LogFormat "%{User-agent}i" agent 507 | 508 | # "combinedio" includes actual counts of actual bytes received (%I) and sent (%O); this 509 | # requires the mod_logio module to be loaded. 510 | #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio 511 | 512 | # 513 | # The location and format of the access logfile (Common Logfile Format). 514 | # If you do not define any access logfiles within a 515 | # container, they will be logged here. Contrariwise, if you *do* 516 | # define per- access logfiles, transactions will be 517 | # logged therein and *not* in this file. 518 | # 519 | #CustomLog logs/access_log common 520 | 521 | # 522 | # If you would like to have separate agent and referer logfiles, uncomment 523 | # the following directives. 524 | # 525 | #CustomLog logs/referer_log referer 526 | #CustomLog logs/agent_log agent 527 | 528 | # 529 | # For a single logfile with access, agent, and referer information 530 | # (Combined Logfile Format), use the following directive: 531 | # 532 | CustomLog logs/access_log combined 533 | 534 | # 535 | # Optionally add a line containing the server version and virtual host 536 | # name to server-generated pages (internal error documents, FTP directory 537 | # listings, mod_status and mod_info output etc., but not CGI generated 538 | # documents or custom error documents). 539 | # Set to "EMail" to also include a mailto: link to the ServerAdmin. 540 | # Set to one of: On | Off | EMail 541 | # 542 | ServerSignature On 543 | 544 | # 545 | # Aliases: Add here as many aliases as you need (with no limit). The format is 546 | # Alias fakename realname 547 | # 548 | # Note that if you include a trailing / on fakename then the server will 549 | # require it to be present in the URL. So "/icons" isn't aliased in this 550 | # example, only "/icons/". If the fakename is slash-terminated, then the 551 | # realname must also be slash terminated, and if the fakename omits the 552 | # trailing slash, the realname must also omit it. 553 | # 554 | # We include the /icons/ alias for FancyIndexed directory listings. If you 555 | # do not use FancyIndexing, you may comment this out. 556 | # 557 | Alias /icons/ "/var/www/icons/" 558 | 559 | 560 | Options Indexes MultiViews FollowSymLinks 561 | AllowOverride None 562 | Order allow,deny 563 | Allow from all 564 | 565 | 566 | # 567 | # WebDAV module configuration section. 568 | # 569 | 570 | # Location of the WebDAV lock database. 571 | DAVLockDB /var/lib/dav/lockdb 572 | 573 | 574 | # 575 | # ScriptAlias: This controls which directories contain server scripts. 576 | # ScriptAliases are essentially the same as Aliases, except that 577 | # documents in the realname directory are treated as applications and 578 | # run by the server when requested rather than as documents sent to the client. 579 | # The same rules about trailing "/" apply to ScriptAlias directives as to 580 | # Alias. 581 | # 582 | ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" 583 | 584 | # 585 | # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased 586 | # CGI directory exists, if you have that configured. 587 | # 588 | 589 | AllowOverride None 590 | Options None 591 | Order allow,deny 592 | Allow from all 593 | 594 | 595 | # 596 | # Redirect allows you to tell clients about documents which used to exist in 597 | # your server's namespace, but do not anymore. This allows you to tell the 598 | # clients where to look for the relocated document. 599 | # Example: 600 | # Redirect permanent /foo http://www.example.com/bar 601 | 602 | # 603 | # Directives controlling the display of server-generated directory listings. 604 | # 605 | 606 | # 607 | # IndexOptions: Controls the appearance of server-generated directory 608 | # listings. 609 | # 610 | IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable Charset=UTF-8 611 | 612 | # 613 | # AddIcon* directives tell the server which icon to show for different 614 | # files or filename extensions. These are only displayed for 615 | # FancyIndexed directories. 616 | # 617 | AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip 618 | 619 | AddIconByType (TXT,/icons/text.gif) text/* 620 | AddIconByType (IMG,/icons/image2.gif) image/* 621 | AddIconByType (SND,/icons/sound2.gif) audio/* 622 | AddIconByType (VID,/icons/movie.gif) video/* 623 | 624 | AddIcon /icons/binary.gif .bin .exe 625 | AddIcon /icons/binhex.gif .hqx 626 | AddIcon /icons/tar.gif .tar 627 | AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv 628 | AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip 629 | AddIcon /icons/a.gif .ps .ai .eps 630 | AddIcon /icons/layout.gif .html .shtml .htm .pdf 631 | AddIcon /icons/text.gif .txt 632 | AddIcon /icons/c.gif .c 633 | AddIcon /icons/p.gif .pl .py 634 | AddIcon /icons/f.gif .for 635 | AddIcon /icons/dvi.gif .dvi 636 | AddIcon /icons/uuencoded.gif .uu 637 | AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl 638 | AddIcon /icons/tex.gif .tex 639 | AddIcon /icons/bomb.gif core 640 | 641 | AddIcon /icons/back.gif .. 642 | AddIcon /icons/hand.right.gif README 643 | AddIcon /icons/folder.gif ^^DIRECTORY^^ 644 | AddIcon /icons/blank.gif ^^BLANKICON^^ 645 | 646 | # 647 | # DefaultIcon is which icon to show for files which do not have an icon 648 | # explicitly set. 649 | # 650 | DefaultIcon /icons/unknown.gif 651 | 652 | # 653 | # AddDescription allows you to place a short description after a file in 654 | # server-generated indexes. These are only displayed for FancyIndexed 655 | # directories. 656 | # Format: AddDescription "description" filename 657 | # 658 | #AddDescription "GZIP compressed document" .gz 659 | #AddDescription "tar archive" .tar 660 | #AddDescription "GZIP compressed tar archive" .tgz 661 | 662 | # 663 | # ReadmeName is the name of the README file the server will look for by 664 | # default, and append to directory listings. 665 | # 666 | # HeaderName is the name of a file which should be prepended to 667 | # directory indexes. 668 | ReadmeName README.html 669 | HeaderName HEADER.html 670 | 671 | # 672 | # IndexIgnore is a set of filenames which directory indexing should ignore 673 | # and not include in the listing. Shell-style wildcarding is permitted. 674 | # 675 | IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t 676 | 677 | # 678 | # DefaultLanguage and AddLanguage allows you to specify the language of 679 | # a document. You can then use content negotiation to give a browser a 680 | # file in a language the user can understand. 681 | # 682 | # Specify a default language. This means that all data 683 | # going out without a specific language tag (see below) will 684 | # be marked with this one. You probably do NOT want to set 685 | # this unless you are sure it is correct for all cases. 686 | # 687 | # * It is generally better to not mark a page as 688 | # * being a certain language than marking it with the wrong 689 | # * language! 690 | # 691 | # DefaultLanguage nl 692 | # 693 | # Note 1: The suffix does not have to be the same as the language 694 | # keyword --- those with documents in Polish (whose net-standard 695 | # language code is pl) may wish to use "AddLanguage pl .po" to 696 | # avoid the ambiguity with the common suffix for perl scripts. 697 | # 698 | # Note 2: The example entries below illustrate that in some cases 699 | # the two character 'Language' abbreviation is not identical to 700 | # the two character 'Country' code for its country, 701 | # E.g. 'Danmark/dk' versus 'Danish/da'. 702 | # 703 | # Note 3: In the case of 'ltz' we violate the RFC by using a three char 704 | # specifier. There is 'work in progress' to fix this and get 705 | # the reference data for rfc1766 cleaned up. 706 | # 707 | # Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) 708 | # English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) 709 | # Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) 710 | # Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) 711 | # Norwegian (no) - Polish (pl) - Portugese (pt) 712 | # Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) 713 | # Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) 714 | # 715 | AddLanguage ca .ca 716 | AddLanguage cs .cz .cs 717 | AddLanguage da .dk 718 | AddLanguage de .de 719 | AddLanguage el .el 720 | AddLanguage en .en 721 | AddLanguage eo .eo 722 | AddLanguage es .es 723 | AddLanguage et .et 724 | AddLanguage fr .fr 725 | AddLanguage he .he 726 | AddLanguage hr .hr 727 | AddLanguage it .it 728 | AddLanguage ja .ja 729 | AddLanguage ko .ko 730 | AddLanguage ltz .ltz 731 | AddLanguage nl .nl 732 | AddLanguage nn .nn 733 | AddLanguage no .no 734 | AddLanguage pl .po 735 | AddLanguage pt .pt 736 | AddLanguage pt-BR .pt-br 737 | AddLanguage ru .ru 738 | AddLanguage sv .sv 739 | AddLanguage zh-CN .zh-cn 740 | AddLanguage zh-TW .zh-tw 741 | 742 | # 743 | # LanguagePriority allows you to give precedence to some languages 744 | # in case of a tie during content negotiation. 745 | # 746 | # Just list the languages in decreasing order of preference. We have 747 | # more or less alphabetized them here. You probably want to change this. 748 | # 749 | LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW 750 | 751 | # 752 | # ForceLanguagePriority allows you to serve a result page rather than 753 | # MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) 754 | # [in case no accepted languages matched the available variants] 755 | # 756 | ForceLanguagePriority Prefer Fallback 757 | 758 | # 759 | # Specify a default charset for all content served; this enables 760 | # interpretation of all content as UTF-8 by default. To use the 761 | # default browser choice (ISO-8859-1), or to allow the META tags 762 | # in HTML content to override this choice, comment out this 763 | # directive: 764 | # 765 | AddDefaultCharset UTF-8 766 | 767 | # 768 | # AddType allows you to add to or override the MIME configuration 769 | # file mime.types for specific file types. 770 | # 771 | #AddType application/x-tar .tgz 772 | 773 | # 774 | # AddEncoding allows you to have certain browsers uncompress 775 | # information on the fly. Note: Not all browsers support this. 776 | # Despite the name similarity, the following Add* directives have nothing 777 | # to do with the FancyIndexing customization directives above. 778 | # 779 | #AddEncoding x-compress .Z 780 | #AddEncoding x-gzip .gz .tgz 781 | 782 | # If the AddEncoding directives above are commented-out, then you 783 | # probably should define those extensions to indicate media types: 784 | # 785 | AddType application/x-compress .Z 786 | AddType application/x-gzip .gz .tgz 787 | 788 | # 789 | # MIME-types for downloading Certificates and CRLs 790 | # 791 | AddType application/x-x509-ca-cert .crt 792 | AddType application/x-pkcs7-crl .crl 793 | 794 | # 795 | # AddHandler allows you to map certain file extensions to "handlers": 796 | # actions unrelated to filetype. These can be either built into the server 797 | # or added with the Action directive (see below) 798 | # 799 | # To use CGI scripts outside of ScriptAliased directories: 800 | # (You will also need to add "ExecCGI" to the "Options" directive.) 801 | # 802 | #AddHandler cgi-script .cgi 803 | 804 | AddHandler php5-script .php 805 | AddType text/html .php 806 | 807 | 808 | # 809 | # For files that include their own HTTP headers: 810 | # 811 | #AddHandler send-as-is asis 812 | 813 | # 814 | # For type maps (negotiated resources): 815 | # (This is enabled by default to allow the Apache "It Worked" page 816 | # to be distributed in multiple languages.) 817 | # 818 | AddHandler type-map var 819 | 820 | # 821 | # Filters allow you to process content before it is sent to the client. 822 | # 823 | # To parse .shtml files for server-side includes (SSI): 824 | # (You will also need to add "Includes" to the "Options" directive.) 825 | # 826 | AddType text/html .shtml 827 | AddOutputFilter INCLUDES .shtml 828 | 829 | # 830 | # Action lets you define media types that will execute a script whenever 831 | # a matching file is called. This eliminates the need for repeated URL 832 | # pathnames for oft-used CGI file processors. 833 | # Format: Action media/type /cgi-script/location 834 | # Format: Action handler-name /cgi-script/location 835 | # 836 | 837 | # 838 | # Customizable error responses come in three flavors: 839 | # 1) plain text 2) local redirects 3) external redirects 840 | # 841 | # Some examples: 842 | #ErrorDocument 500 "The server made a boo boo." 843 | #ErrorDocument 404 /missing.html 844 | #ErrorDocument 404 "/cgi-bin/missing_handler.pl" 845 | #ErrorDocument 402 http://www.example.com/subscription_info.html 846 | # 847 | 848 | # 849 | # Putting this all together, we can internationalize error responses. 850 | # 851 | # We use Alias to redirect any /error/HTTP_.html.var response to 852 | # our collection of by-error message multi-language collections. We use 853 | # includes to substitute the appropriate text. 854 | # 855 | # You can modify the messages' appearance without changing any of the 856 | # default HTTP_.html.var files by adding the line: 857 | # 858 | # Alias /error/include/ "/your/include/path/" 859 | # 860 | # which allows you to create your own set of files by starting with the 861 | # /var/www/error/include/ files and 862 | # copying them to /your/include/path/, even on a per-VirtualHost basis. 863 | # 864 | Include conf.d/*.conf 865 | 866 | Alias /error/ "/var/www/error/" 867 | 868 | 869 | 870 | 871 | AllowOverride None 872 | Options IncludesNoExec 873 | AddOutputFilter Includes html 874 | AddHandler type-map var 875 | Order allow,deny 876 | Allow from all 877 | LanguagePriority en es de fr 878 | ForceLanguagePriority Prefer Fallback 879 | 880 | 881 | # ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var 882 | # ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var 883 | # ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var 884 | # ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var 885 | # ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var 886 | # ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var 887 | # ErrorDocument 410 /error/HTTP_GONE.html.var 888 | # ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var 889 | # ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var 890 | # ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var 891 | # ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var 892 | # ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var 893 | # ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var 894 | # ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var 895 | # ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var 896 | # ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var 897 | # ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var 898 | 899 | 900 | 901 | 902 | # 903 | # The following directives modify normal HTTP response behavior to 904 | # handle known problems with browser implementations. 905 | # 906 | BrowserMatch "Mozilla/2" nokeepalive 907 | BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 908 | BrowserMatch "RealPlayer 4\.0" force-response-1.0 909 | BrowserMatch "Java/1\.0" force-response-1.0 910 | BrowserMatch "JDK/1\.0" force-response-1.0 911 | 912 | # 913 | # The following directive disables redirects on non-GET requests for 914 | # a directory that does not include the trailing slash. This fixes a 915 | # problem with Microsoft WebFolders which does not appropriately handle 916 | # redirects for folders with DAV methods. 917 | # Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. 918 | # 919 | BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully 920 | BrowserMatch "MS FrontPage" redirect-carefully 921 | BrowserMatch "^WebDrive" redirect-carefully 922 | BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully 923 | BrowserMatch "^gnome-vfs/1.0" redirect-carefully 924 | BrowserMatch "^XML Spy" redirect-carefully 925 | BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully 926 | 927 | # 928 | # Allow server status reports generated by mod_status, 929 | # with the URL of http://servername/server-status 930 | # Change the ".example.com" to match your domain to enable. 931 | # 932 | # 933 | # SetHandler server-status 934 | # Order deny,allow 935 | # Deny from all 936 | # Allow from .example.com 937 | # 938 | 939 | # 940 | # Allow remote server configuration reports, with the URL of 941 | # http://servername/server-info (requires that mod_info.c be loaded). 942 | # Change the ".example.com" to match your domain to enable. 943 | # 944 | # 945 | # SetHandler server-info 946 | # Order deny,allow 947 | # Deny from all 948 | # Allow from .example.com 949 | # 950 | 951 | # 952 | # Proxy Server directives. Uncomment the following lines to 953 | # enable the proxy server: 954 | # 955 | # 956 | #ProxyRequests On 957 | # 958 | # 959 | # Order deny,allow 960 | # Deny from all 961 | # Allow from .example.com 962 | # 963 | 964 | # 965 | # Enable/disable the handling of HTTP/1.1 "Via:" headers. 966 | # ("Full" adds the server version; "Block" removes all outgoing Via: headers) 967 | # Set to one of: Off | On | Full | Block 968 | # 969 | #ProxyVia On 970 | 971 | # 972 | # To enable a cache of proxied content, uncomment the following lines. 973 | # See http://httpd.apache.org/docs/2.2/mod/mod_cache.html for more details. 974 | # 975 | # 976 | # CacheEnable disk / 977 | # CacheRoot "/var/cache/mod_proxy" 978 | # 979 | # 980 | 981 | # 982 | # End of proxy directives. 983 | 984 | ### Section 3: Virtual Hosts 985 | # 986 | # VirtualHost: If you want to maintain multiple domains/hostnames on your 987 | # machine you can setup VirtualHost containers for them. Most configurations 988 | # use only name-based virtual hosts so the server doesn't need to worry about 989 | # IP addresses. This is indicated by the asterisks in the directives below. 990 | # 991 | # Please see the documentation at 992 | # 993 | # for further details before you try to setup virtual hosts. 994 | # 995 | # You may use the command line option '-S' to verify your virtual host 996 | # configuration. 997 | 998 | # 999 | # Use name-based virtual hosting. 1000 | # 1001 | #NameVirtualHost *:80 1002 | # 1003 | # NOTE: NameVirtualHost cannot be used without a port specifier 1004 | # (e.g. :80) if mod_ssl is being used, due to the nature of the 1005 | # SSL protocol. 1006 | # 1007 | 1008 | # 1009 | # VirtualHost example: 1010 | # Almost any Apache directive may go into a VirtualHost container. 1011 | # The first VirtualHost section is used for requests without a known 1012 | # server name. 1013 | # 1014 | # 1015 | # ServerAdmin webmaster@dummy-host.example.com 1016 | # DocumentRoot /www/docs/dummy-host.example.com 1017 | # ServerName dummy-host.example.com 1018 | # ErrorLog logs/dummy-host.example.com-error_log 1019 | # CustomLog logs/dummy-host.example.com-access_log common 1020 | # 1021 | --------------------------------------------------------------------------------