MRTG配置

来源:百度文库 编辑:神马文学网 时间:2024/04/25 23:50:23
MRTG(Multi Router Traffic Grapher)是多路由器流量图表绘制器。它是一个用来监视网络链路的流量负载的工具。MRTG能够生成包含当前流量真实图形表示的PNG图像的HTML页面。
MRTG是什么玩意?
MRTG的基本用途介绍。
MRTG(Multi Router Traffic Grapher)是多路由器流量图表绘制器。
MRTG是一个用来监视网络链路的流量负载的工具。
MRTG能够生成包含当前流量真实图形表示的PNG图像的HTML页面。
MRTG的安装与使用
如何安装和使用MRTG
安装前的准备
MRTG依赖库的编译
MRTG的编译
MRTG的配置
运行MRTG
安装前的准备
要编译和使用mrtg,需要有C编译器和安装好的perl。大多数情况下,开发人员使用的机器上都已经有了这两项工具。如果还没有装好,现在就得把他们装好。以下会介绍整个编译的详细过程。
GCC
GNU的C编译器。http://gcc.gnu.org/
Perl
MRTG系统的很大一部分都是使用Perl脚本语言编写的。请确认已安装了最新的perl版本。至少需要perl 5.005以上的版本才能正常工作。可在http://www.perl.com/ 上下载最新版本。
MRTG生成的流量图表使用PNG格式。要使用该格式,需要几个第三方的库来支持。编译这些库的时候,建议你使用静态库来链接。如果用静态库,可以避免许多头痛的问题。详细情况请参看下一章节。注意许多机器已建安装有所需的各种库,完全没有必要再装一套。最好跳过下面关于库的介绍部分,试试直接进行mrtg的编译来验证一下你的机器是否已经装好了所需要的数据库。
如果初次尝试失败了,请按一下说明的步骤对所有所需要的数据库进行重新编译。
gd
gd函数库,是由Thomas Boutell创建的基础图形绘制库。注意1.3版本以后的发布版仅仅创建PNG图像。主要是因为 a) GIF格式需要采用Unisys公司专利的压缩技术,Thomas本人不想因为自找麻烦。b) PNG比其他格式根据高效,并且没有专利限制。MRTG可以使用旧的或新的GD函数库。最新版的GD函数库可以在http://www.boutell.com/gd/ 中下载。
libpng
gd函数库库所需要的用来生成PNG图像文件的函数库。请从http://www.libpng.org/pub/png/libpng.html 中下载最新版本的libpng函数库。
zlib
libpng需要的用来压缩图像文件的压缩函数库。在http://www.gzip.org/zlib 中下载。
当然,你还得需要mrtg本身的代码。http://people.ee.ethz.ch/~oetiker/webtools/mrtg/pub/ 中可以下载最新版本。
MRTG依赖库的编译
In this section I will give you step by step instructions on how to compile the various libraries required for the compilation of mrtg. Note that these libaries may already be installed if you have a BSD or Linux system so you can skip recompiling them. The wget program used below is a simple web downloader. You can also enter the address into your netscape if you don‘t have wget available.
First let‘s create a directory for the compilation. Note that this may already exist on your system. No problem, just use it.
mkdir -p /usr/local/src cd /usr/local/src
If you do not have zlib installed
wget http://www.gzip.org/zlib/zlib-1.1.4.tar.gz gunzip -c zlib-*.tar.gz | tar xf - rm zlib-*.tar.gz mv zlib-* zlib cd zlib ./configure make cd ..
If you don‘t have libpng installed
wget http://public.planetmirror.com/pub/sourceforge/l/li/libpng/libpng-1.0.15.tar.gz gunzip -c libpng-*.tar.gz |tar xf - rm libpng-*.tar.gz mv libpng-* libpng cd libpng make -f scripts/makefile.std CC=gcc ZLIBLIB=../zlib ZLIBINC=../zlib rm *.so.* *.so cd ..
And now you can compile gd
For versions up to 1.8.4, try:
wget http://www.boutell.com/gd/http/gd-1.8.4.tar.gz gunzip -c gd-*.tar.gz |tar xf - rm gd-*.tar.gz mv gd-* gd cd gd
The characters at the end of the following lines mean that all the following material should actually be written on a single line.
perl -i~ -p -e s/gd_jpeg.o//g Makefile make INCLUDEDIRS="-I. -I../zlib -I../libpng" LIBDIRS="-L../zlib -L. -L../libpng" LIBS="-lgd -lpng -lz -lm" CFLAGS="-O -DHAVE_LIBPNG" cd ..
For version starting around 2.0.11, try:
wget http://www.boutell.com/gd/http/gd-2.0.11.tar.gz gunzip -c gd-2.0.11.tar.gz |tar xf - mv gd-2.0.11 gd cd gd env CPPFLAGS="-I../zlib -I../libpng" LDFLAGS="-L../zlib -L../libpng" ./configure --disable-shared --without-freetype --without-jpeg make cp .libs/* .
MRTG的编译
Ok, now everything is ready for the mrtg compilation.
cd /usr/local/src gunzip -c mrtg-2.12.2.tar.gz | tar xvf - cd mrtg-2.12.2
If all the libraries have been preinstalled on your system you can configure mrtg by doing a simple:
./configure --prefix=/usr/local/mrtg-2
Otherwise you may have to give some hints on where to find the various libraries required to compile mrtg:
./configure --prefix=/usr/local/mrtg-2 --with-gd=/usr/local/src/gd --with-z=/usr/local/src/zlib --with-png=/usr/local/src/libpng
If you have RRDtool available you might want to tell mrtg about it so that you can opt to use rrdtool with mrtg. Check the mrtg-rrd manpage.
Configure will make sure your environment is fit for building mrtg. If it finds a problem, it will tell you so and it will also tell you what to do about it. If everything is OK, you will end up with a custom Makefile for your system. Now type:
make
This builds the rateup binary and edits all the perl pathnames in the scripts. You can now install mrtg by typing:
make install (requires gnu install)
All the software required by MRTG is now installed under the /usr/local/mrtg-2 subdirectory.
You can now safely delete the libraries we compiled above. Then again, you might want to keep them around so that you have them available when compiling the next version of mrtg.
MRTG的配置
下一步是配置mrtg来监视网络设备。配置是通过建立一个定义需要监视内容的mrtg.cfg文件来进行的。幸运的是你不需要直接自行编写配置文件。mrtg附带有一个cfgmaker工具,他会帮助你编写配置文件,并自动生成配置文件。在bin子目录下可以看到该脚本。
cfgmaker --global ‘WorkDir: /home/httpd/mrtg‘ --global ‘Options[_]: bits,growright‘ --output /home/mrtg/cfg/mrtg.cfg community@router.abc.xyz
上例中会在/home/mrtg/cfg目录中创建一个mrtg的配置文件(假定该目录在你的web服务器上是可见的).你可以在cfgmaker的manpage中查看到所有关于cfgmaker的信息。其中--ifref=ip选项是一个可以避免接口重编号麻烦的选项。
If you want to start rolling your own mrtg configuration files, make sure you read the mrtg-reference manpage to learn all about the possible configuration options.
如果想现在就试试mrtg的配置文件,请你先读一读mrtg的手册,学一学mrtg所有可能的选项。
运行MRTG
创建好了配置文件后,就可以这样来运行mrtg:
/usr/local/mrtg-2/bin/mrtg /home/mrtg/cfg/mrtg.cfg
This will query your router and also create your first mrtg trafic graphs and webpages. When you run mrtg for the first time there will be a lot of complaints about missing log files. Don‘t worry, this is normal for the first 2 times you start mrtg. If it keeps complaining after this time you might want to look into the problem.
上面的命令会查询你的路由器并创建你的第一个mrtg流量图表和web页面。在你第一次运行mrtg时,会出现许多关于缺少日志文件的提示信息。不要担心,在你前2次运行mrtg的时候出现这种情况时正常的。如果此后仍然出现这样的提示信息,你就要查看存在的问题了。
手工启动mrtg对于长时间的运行来说是不够理想的。因此,如果你对mrtg生成的结果满意了,你就可以按照固定的间隔自动运行mrtg(就是说缺省情况下每5分钟运行一次)。
你还可以用下面的格式通过unix的cron定时调度程度来定时自行mrtg:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /mrtg /mrtg.cfg --logging /var/log/mrtg.log
或者如果你使用的是linux,可以用下面的cron -e 命令格式来设置:
*/5 * * * * /mrtg /mrtg.cfg --logging /var/log/mrtg.log
或者按照下面的方式使用/etc/crontab来定时调度:
*/5 * * * * mrtg-user /mrtg /mrtg.cfg --logging /var/log/mrtg.log
你还可以在配置文件中加入下面的行,使得mrtg以守护程序的方式持续运行:
RunAsDaemon: Yes
然后通过创建一个系统的启动脚本来自动启动。不过,不同的unix系统的启动脚本差异很大。现代的unix系统通常有一个/etc/init.d或者是/etc/rc.d/init.d目录,存放系统引导时需要自动启动的脚本。你还可以在/etc/rc3.d 或/etc/rc.d/rc?.d中创建S65mrtg文件。如果无法确定用那种方式好的话,先看看系统文档吧。
放入init.d目录的小脚本可以是这样的:
#! /bin/sh cd /usr/local/mrtg-2.12.2/bin && ./mrtg --user=mrtg-user /home/httpd/mrtg/mrtg.cfg --logging /var/log/mrtg.log
注意这样的脚本只有在你的mrtg.cfg文件中有 RunAsDaemon: Yes 的选项设置时能够正常工作。
MRTG配置文件的生成工具cfgmaker
如何使用cfgmaker工具来创建你所需要的metg的配置文件。
cfgmaker的说明
配置
过滤器的详细介绍预定义的过滤器名称
各种过滤器的例子
模板详细介绍可写的模板变量
预定义的模板变量主机和系统相关的变量
接口目标相关的变量
接口网络配置变量
接口名称/描述以及别名变量
模板的助手函数
模板文件的例子Template Example 1: Eliminating Rejected Targets From Appearing
Template Example 2: Simplier Version of Example 1
Template Example 3: Creating CPU Targets for Hosts
实例
cfgmaker的说明
cfgmaker根据某个路由器或其他SNMP可管理设备获取的信息来创建MRTG的配置文件。:
[community@]router
Coomunity是你所创建配置文件的设别的community名称。如果没有指定,缺省为 ‘public‘ ; 如果你不知道某个设备的community名称,可以先试试这个设备。如果使用的community名称不正确,将无法从设备中获得任何响应信息。
路由器是SNMP可管理设备的IP地址或者是DNS域名。你可以为该名称用 : 分割来指定6项更多的选项。语法如下::
router[:[prt][:[tmout][:[retr][:[backoff][:vers]]]]]
特别有意思的是最后一项参数, vers 。如果将该参数设置为 2 , 将通过SNMP V2来查询你的设备。它允许你提取设备中的64位的流量计数器,并且对于快速的接口来说能够更加有效(不会有计数器溢出情况的发生)。注意在命令行中的router出现的顺序与所生成的配置文件中的参数顺序一致。第一个指定的router其配置文件的配置信息行将首先被生成,其后的配置行是下一个router的,以此类推。
注意cfg配置文件的第一行会包含要来生成配置文件使用的所有命令行选项。这主要是为了然后在增加新主机或进行其他全局修改时,能够很容易地再次生成配置文件。
配置
除了 --output 和 --global 选项以外,其他所有的选项仅仅影响命令行中跟在其后的router。如果命令行中的某个选项在后面再次以其他值出现,新的值将覆盖旧的值并对后续的router起作用。这样选项可以为路由器组或者独立的路由器进行裁减。
参看 --output 和 --global 选项来了解其在命令行中何处出现、出现次数如何影响所生成的配置文件。
参看后面给出的例子来了解如何为多个路由器设置不同的选项。
--help 打印帮助信息并退出。
--man 打印手册信息并退出。
--version 打印cfgmaker的版本信息。cfgmaker的版本应当与所使用的mrtg的版本一致。
--ifref nr|ip|eth|descr|name
选择接口识别方式。缺省为 nr ,表示通过路由器编号来识别路由器的接口。不幸的是SNMP树中的接口编号是可以改变的。某些路由器会在增加新的接口后更改其编号,另一些更搞笑,他们会在每次月圆的的日子更改他们的编号。
为了搞定这样令人沮丧的问题,mrtg能够通过其他4中属性来识别接口。这四种方式没有一种能够适用与所有的接口,不过你可以选一种适合你的方式。注意特别是某些路由器的所有接口卡都用相同的以太网地址,从而导致问题频出。
Select ip to identify the interface by its IP number. Use eth to use the ethernet address for identification. Use descr to use the Interface description. Or use name to use the Interface name.
If your chosen method does not allow unique interface identification on the device you are querying, cfgmaker will tell you about it.
--ifdesc nr|ip|eth|descr|name|type|alias
Select what to use as the description of the interface. The description appears in the Title[] property for the target as well as the text header in the HTML code defined in the target‘s PageTop[]. Default is to use nr which is just the interface number which isn‘t always useful to the viewer of the graphs.
There are 6 other properties which could be used. Use ip if you want to use the interface‘s IP-address. Use eth if you want to use the interface‘s ethernet address. If you want a better description, you can use either descr, name or alias. Exactly what each of these do varies between different equipment so you might need to experiment. For instance, for a serial interface on a Cisco router running IOS using name might result in "S0" being the interface description , descr might result in "Serial0" and alias might result in "Link to HQ" (provided that is what is used as the interface‘s description in the router‘s configuration).
Finally, if you want to describe the interface by it‘s Btype (i.e "ethernetCSMA", "propPointtoPoint" etc) you can use type.
--if-filter ‘filter-expression‘
First of all, this is under some developement and is experimental.
Use this if you want to have better control over what interfaces gets included into the configuration. The filter-expression is evaluated as a piece of Perl code and is expected to return a truth value. If true, include the interface and if false, exclude the interface.
For a further discussion on how these filters work, see the section DETAILS ON FILTERS below.
--if-template ‘template-file‘
First of all, this is under some development and is experimental.
Use this if you want to control what the line for each target should look like in the configuration file. The contents of the file template-file will be evaluated as a Perl program which generates the lines using certain variables for input and output.
For a further discussion on how these templates work, see the section DETAILS ON TEMPLATES below.
--host-template ‘template-file‘
First of all, this is under some development and is experimental.
Use this if you want to have some extra targets related to the host itself such as CPU utilization, ping response time to the host, number of busy modems etc. The contents of the file template-file will be evaluated once per host as a Perl program which generates the lines using certain variables for input and output.
For a further discussion on how these templates work, see the section DETAILS ON TEMPLATES below.
--community ‘community-string‘
Use this to set the community for the routers following on the command line to community-string. Individual routers might overrride this community string by using the syntaxcommunity@router.
--enable-ipv6
This option enables IPv6 support. It requires the appropriate perl modules; if they are not found then IPv6 is disabled (see the ipv6 documentation).
cfgmaker will use IPv6 or IPv4 depending on the target. If the target is a numeric address, the protocol depends on the type of address. If the target is a hostname, cfgmaker will try to resolve the name first to an IPv6 address then to an IPv4 address.
IPv6 numeric addresses must be specified between square braces.
For example:
cfgmaker --enable-ipv6 [2001:760:4::1]:165:::2
If the target has both an IPv6 address and an IPv4 address with the same hostname, cfgmaker first queries the target using IPv6 and falls back to IPv4 if it fails. This is useful for targets which don‘t support SNMP over IPv6.
--use-16bit This option forces the use of 16bit SNMP request IDs. Some broken SNMP agents do not accept 32bit request IDs. Try to avoid this option as much as possible, complain to your agent vendor instead.
--snmp-options :[port][:[timeout][:[retries][:[backoff][:version]]]]
Use this to set the default SNMP options for all routers following on the command line. Individual values might be omitted as well as trailing colons. Note that routers might override individual (or all) values specified by --snmp-options by using the syntax
router[:[port][:[timeout][:[retries][:[backoff][:version]]]]]
--global bla: abc
Use this to add global options to the generated config file. You can call --global several times to add multiple options. The line will appear in the configuration just before the config for the next router appearing on the command line.
--global "workdir: /home/mrtg"
If you want some default Options you might want to put
--global "options[_]: growright,bits"
Specifying --global after the last router on the command line will create a line in the configuration file which will appear after all the routers.
--noreversedns Do not try to reverse lookup IP numbers ... a must for DNS free environments.
--no-down Normally cfgmaker will not include interfaces which are marked anything but administratively and operationally UP. With this switch you get them all.
--show-op-down Include interfaces which are operatively down.
--zero-speed speed
Assign this speed in bits-per-second to all interfaces which return 0 for ifSpeed and ifHighSpeed. Some switches, notably Foundry equipment, return a speed of zero for some interfaces. For example, to have all interfaces reporting zero set to 100Mbps, use --zero-speed=100000000.
--subdirs format
Give each router its own subdirectory for the HTML and graphics (or .rrd) files. The directory name is the given format string with a couple of pattern replacements. The string HOSTNAME will be replaced by the hostname of the router (however you specified it on the cfgmaker commandline -- it may be an actual hostname or just an IP address), and SNMPNAME will be replaced with the device‘s idea of its own name (the same name that appears on the right side of the Title lines). For instance, a call like:
cfgmaker --subdirs=HOSTNAME__SNMPNAME public@10.10.0.18
would result in the generation of lines looking something like:
Directory[10.10.0.18_1]: 10.10.0.18__fp2200-bothrip-1.3
--output file Write the output from cfgmaker into the file file. The default is to use STDOUT. --output is expected to appear only once on the command line. If used multiple times, the file specified by the last --output will be used.
--nointerfaces
Don‘t generate configuration lines for interfaces.
This makes cfgmaker skip all steps related to interfaces which means it will not do any polling of the router to retrieve interface information which speeds up the execution of cfgmaker and it will neither run any interface templates.
--interfaces
This makes cfgmaker generate configuration lines for interfaces (the default behaviour).
The main usage of this option is to negate an --nointerfaces appearing earlier on the command line.
过滤器的详细介绍
过滤器的目的是确定接受哪些接口,拒绝哪些接口。这是通过为每个接口执行其过滤器表达式,并根据执行结果来确定的,过滤器表达式是一小段perl代码。如果执行结果为 true , 则接受该接口,否则拒绝。
在使用过滤器时,要记住perl有自己的 true 和 false 的判断标准。 空串和 字符串 0 都是 false 。 整数值 0 以及其他任何未定义的值都是 false 。 任何应用都是 true.
由于过滤器是perl代码,以下perl表达式需要了解。:
表达式可以用括号分组 () . 表达式可以用以下布尔操作符进行组合。
and (equivalent with && )
Boolean and of the two expressions, is only true if both expressions are true. Example: expression1 and expression2
or (equivalent with || )
Boolean or of the two expressions, is true if either or both expressions are true. Example: expression1 or expression2
not (equivalent with ! )
Boolean negation of a single expression. Example: not expression . Yet another example: !expression
(For more details on this I recommend a book on Perl)
预定义的过滤器名称
为了方便起见,在过滤器中有许多预定义的变量。注意这些变量在接口模板中同样可用。(不是主模板)
Caveat: All these variables‘ names begin with a dollar sign ($), which is a syntactic requirement for scalar variables in Perl. The danger here is that the dollar sign in many shells is an active character (often used for shell variables exactly as in Perl variables) so it is important to ensure that the Perl expression isn‘t evaluated by the command line shell as shell code before being passed to cfgmaker as command line arguments. In shells like Bourne shell, ksh shell or bash shell, placing the entire expression within single qoutes will avoid such accidental evaluation:
--if-filter=($default_iftype && $if_admin) $if_type
This is an integer specifying the interface type as per the SNMP standards and as reported by the polled device. A complete list of interface types would be impractical for this document , but there are a number predefined varables below. Normally, cfgmaker puts in the target‘s PageTop this iftype value within paranthesis after the name of the interface type. (e.g propPointToPointSerial (22) ).
Here‘s a list of some of the most common interface types by number:
6 ethernetCsmacd 7 iso88023Csmacd 9 iso88025TokenRing 15 fddi 19 E1 20 basicISDN 21 primaryISDN 22 propPointToPointSerial 23 ppp 24 softwareLoopback 30 ds3 32 frame-relay 33 rs232 37 atm 39 sonet 44 frameRelayService 46 hssi 49 aal5 53 propVirtual 62 Fast Ethernet (100BaseT) 63 ISDN & X.25 69 Full Duplex Fast Ethernet (100BaseFX) 94 Asymetric Digital Subscriber Loop (ADSL) 117 Gigabit Ethernet 134 ATM Sub Interface =item B<$default>
True if and only if cfgmaker normally should accepted the interface based on the interfaces administrative and operational state (taking the flags --no-down and --show-op-down into account) and it‘s type (and a few other things).
$default_ifstate
True if and only if cfgmaker would have accepted the interface based on it‘s operational and administrative states (also taking into account the presence of the flags --no-down and --show-op-down).
$default_iftype
True if and only if cfgmaker would have accepted the interface based on it‘s type (and a few type specific details in addition).
$if_admin
True if and only if the interface is in an adminstrative up state.
$if_oper
True if and only if the interface is in an operational up state.
A number of variables are also predefined to easily decide if an interface belong to a certain cathegory or not. Below is all those variables listed together with which if_type numbers each variable will be true for. Note that some variables refer to other variables as well.
$if_is_ethernet
True for ethernet interfaces (nr 6, 7, 26, 62, 69 and 117).
$if_is_isdn
True for various ISDN interface types (nr 20, 21, 63, 75, 76 and 77)
$if_is_dialup
True for dial-up interfaces such as PPP as well as ISDN. (nr 23, 81, 82 and 108 in addition to the numbers of $if_is_isdn).
$if_is_atm
True for miscellaneous ATM related interface types (nr 37, 49, 107, 105, 106, 114 and 134).
$if_is_wan
True for WAN interfaces point to point, Frame Relay and High Speed Serial ( 22,32,44,46)
$if_is_lan
True for LAN interfaces (8, 9, 11, 15, 26, 55, 59, 60 and 115 in addition to the numbers of $if_is_ethernet).
$if_is_dsl
True for ADSL, RDSL, HDSL and SDSL (nr 94, 95, 96, 97)
$if_is_loopback
True for software loopback interfaces (nr 24)
$if_is_ciscovlan
True for Cisco VLAN interfaces (interfaces with the word Vlan or VLAN in their ifdescs)
$if_vlan_id
Returns the vlan id associated with a specific port on Cisco Catalyst switches under both Catalyst OS and IOS. If it is not a vlan interface, will return undef.
$if_MTU
Returns the Maximum Transfer Unit associated with a specific port.
Besides that, you can also use the variables defined for templates below. Further, all the variables available in cfgmaker is at the scripts disposal even if the use of such features is discouraged. More shortcuts in the form of variables and functions will be made avaiable in the future instead.
各种过滤器的例子
The following filter will not affect which interfaces get‘s included or excluded, it will make cfgmaker behave as normally.
‘--if-filter=$default‘
The following filter will make cfgmaker exclude PPP (23) interfaces:
‘--if-filter=$default && $if_type!=23‘
The following filter will make cfgmaker behave as usual except that it will consider the operational state of an interface irrelevant but still reject all interfaces which are administratively down.:
‘--if-filter=$if_admin && $default_iftype‘
模板详细介绍
The contents of the template files are evaluated as a Perl program. A number or Perl variables are available for the program to read and others are used to be written to.
As quite a few of the predefined variables has values which are are supposed to be used in HTML code some of them have an HTML-escaped`variant, e.g $html_syslocation is the HTML escaped variant of $syslocation. The HTML escaping means that the chars `< , > and & are replaced by < , > and & and that newlines embedded in the string are prepended with
and appended with a space character (if a newline is last in the string it is not touched).
可写的模板变量
These are the variables available to store the configuration lines in. Some of them are initialized prior to the evaluation of the template but such content normally is comments for inclusion in the final configuration file so those variables might be reset to the empty string in the template code to eliminate the comments. The other way around is also possible, the contents of these variables might be extended with further information for various reasons such as debugging etc.
Once the template has been evaluated, the following happens: if the template is a interface template and the actual interface for some reason is rejected and thus needs to be commented out, all the lines in the variable $target_lines are turned into comments by adding a hash mark ( # ) at their beginning. Then all the variables $head_lines, $problem_lines , $target_lines and $separator_lines are concatenated together to form the lines to add to the configuration file.
$target_lines
This variable is the placeholder for the configuration lines created by the template. $target_lines is predefined to be empty when the template code is evaluated.
$head_lines
This variable is intended to be the placeholder for the comment line appearing just before the target in the configuration file. It is initialized with that comment line before the evaluation of the template code and if the template doesn‘t modify $head_lines during evaluation, the comment will look like usual in the config file.
$problem_lines
This variable is intended to be the placholder for the comment lines describing any problems which might have been encountered when trying to add the target into the configuration. For host templates it‘s normally not used and for those it‘s predefined as the empty string. For interface templates $problem_lines is predefined with the error description comments which cfgmaker normally would use for rejected interfaces or as the empty string for accepted interfaces.
It is possible to test against $problem_lines to find out if an interface will be included or rejected but this is not recommended. Test against $if_ok instead.
$separator_lines
This variable is the placeholder for the string to use as the separator between the code for individual targets. The contents of this variable is put after each target (so the lines will appear after the end of the last target in the config as well).
预定义的模板变量
All the variables below are available for interface templates to use. For host templates, only those listed under Host and System Variables are available.
For interface templates the variables listed under Predefined Filter Variables are also available.
主机和系统相关的变量
$router_name
This is the fully qualified name for the router. It is affected by the following items on the command line: the router name itself and --dns-domain.
$router_connect
This is the reference string for the router being polled. It is on the formcommunity@router possibly followed by some snmp options. It is affected by the following items on the command line: the router name itself, --community, --snmp-options and --dns-domain. (There‘s no HTML escaped variant available)
$directory_name
This variable should contain the directory name as cfgmaker normally would use as the value for the Directory[] directive. The value is determined by the --subdirs command line option. If --subdirs isn‘t specified $directory_name will be the empty string. (There‘s no HTML escaped variant available)
$syscontact
This variable is the router‘s SNMP sysContact value. (HTML escaped variant: $html_syscontact)
$sysname
This variable is the router‘s SNMP sysName value. (No HTML escaped variant available)
$syslocation
This variable is the router‘s SNMP sysLocation value. (HTML escaped variant: $html_syslocation)
$sysdescr
This variable is the router‘s SNMP sysDescr value. It is normally not used by cfgmaker but might be useful in a template. (HTML escaped variant: $html_sysdescr)
接口目标相关的变量
$target_name
This is what cfgmaker normally would use as the the name of the target. The target name is what is found within the square brackets, [] , for target directives. (There‘s no HTML escaped variant available)
$if_ref
This the reference string for the interface. It is expected to be used in the Target[xyz] directive to distinguish what interface to use. The value of this variable is affected by the --ifref command line option. It is normally used together with $router_connect. (There‘s no HTML escaped variant available)
$if_ok
This variable is true if the interface is going to be included into the configuration file, otherwise false. Don‘t test against other variables such as $problem_lines to find out if an interface will be rejected or not, use this $if_ok instead.
$default_target_lines
This variable contains all the target lines which cfgmaker by default outputs for this interface. It‘s useful if you want to have the standard target but want to add some extra lines to it by using a template.
By default cfgmaker uses the following directives for each target it generates: Target[], SetEnv[], MaxBytes[], Title[], PageTop[] and if there is any directory specified also the Directory[] directive.
To facilitate the creation of templates which generates target configs which are similar to the default one, each of the above mentioned directive lines have a corresponding variable containing the line as cfgmaker would have output it by default.
Note that none of these have a HTML escaped variant, text in them is HTML escaped where needed. Also note that they do not have any newline at the end.
$default_target_directive
This variable contains the default string for the Target[] directive line.
$default_setenv_directive
This variable contains the default string for the SetEnv[] directive line.
$default_directory_directive
This variable contains the default string for the Directory[] directive line which means it is an empty string (with no newline) if there‘s no directory.
$default_maxbytes_directive
This variable contains the default string for the MaxBytes[] directive line.
$default_title_directive
This variable contains the default string for the Title[] directive line.
$default_pagetop_directive
This variable contains the default string for the PageTop[] directive lines.
接口网络配置变量
$if_ip
This variable should contain the IP-address of the interface, if any has been assigned to it. (There‘s no HTML escaped variant available)
$ifindex
This variable is the SNMP ifIndex for the interface which per definition always is an integer. (There‘s no HTML escaped variant available)
$if_index
Equivalent with $ifindex.
$if_eth
Contains the ethernet address of the interface, if any. (There‘s no HTML escaped variant available)
$if_speed
This variable is the speed in bytes/second (with prefixes). (There‘s no HTML escaped variant available)
$if_speed_str
This variable is a cooked speed description which is either in bits or bytes depending on wether or not the bits option is active and also with the proper prefix for the speed (k, M, G etc). (No HTML escaped variant available)
$if_type_desc
This variable is a textual description of the interface type. (HTML escaped variant: $html_if_type_desc)
$if_type_num
This variable the integer value corresponding to the interface type (for a listing for the value for the more common interface types, see the section DETAILS ON FILTERS above). (No HTML escaped variant available)
$if_dns_name
This is the DNS name for the interface. (No HTML escaped variant available)
接口名称/描述以及别名变量
It might seem confusing with both Name, Description and Alias in this context and to some extent it is. Name and Description are usually supported on most equipment but how they are used varies, both between manufacturers as well as between different cathegories of equipment from the same manufacturer. The Alias is at least supported by Cisco IOS, and that variable contains whatever is used in the IOS statement called description for the interface (not to be confused with the SNMP variables for Description).
For better control from the command line consider $if_title_desc which contents are controlled by the --if-descr command line option.
$if_snmp_descr
This variable should contain the raw description of the interface as determined by the SNMP polling of the router. (HTML escaped variant: $html_if_snmp_descr)
$if_snmp_name
The raw name for the interface as provided by SNMP polling. (HTML escaped variant: $html_if_snmp_name)
$if_snmp_alias
The raw ifAlias for the interface as provided by SNMP polling. (HTML escaped variant: $html_if_snmp_alias)
$if_cisco_descr
The raw CiscolocIfDescr for the interface as provided by SNMP polling. (HTML escaped variant: $html_if_cisco_descr)
$if_description
This is the cooked description string for the interface, taking into account the SNMP values found for the interface‘s RDescr, ifAlias and CiscolocIfDescr. (HTML escaped variant: $html_if_description)
$if_title
The full string cfgmaker by default would have used for the Title[] directive in the configuration as well as the content of the topmost H1 tag in the PageTop[]. Is composed by the contents of $desc_prefix, $if_title_desc and $sysname.
As $if_title depends on $if_title_desc, it is possible to indirectly control $if_title by using the command line option --if-descr.:
(HTML escaped variant: $html_if_title)
$if_port_name
If the host is a Cisco Catalyst LAN switch, this variable is the name of that port. (No HTML escaped variant available)
$desc_prefix
This variable is a prefix of the description of what the target is to use in the Title[] directive and in the H1 section of the PageTop[] . Default is Traffic analysis for . (HTML escaped variant: $html_desc_prefix)
$if_title_desc
This is the description of the interface normally used by cfgmaker as part of the variable $if_title. The latter is used as the full string in the Title[] directove and the H1 section in the PageTop[].
$if_title_desc is controlled by the command line option --if-descr which indirectly controls the contents of $if_title:
(HTML escaped variant: $html_if_title_desc
模板的助手函数
The following functions exists to facilitate the writing of host and interface templates.
html_escape(string)
html_escape() takes a string as an argument and returns a new string where the following substitutions has been done: the chars <`, > and & are replaced by < , > and & and that newlines embedded in the string are prepended with
and appended with a space character (newlines at the end of the string are not touched).
模板文件的例子
Template Example 1: Eliminating Rejected Targets From Appearing
This template file generates exactly the same configuration code per interface as cfgmaker does by default, with the exception that it eliminates all lines (comments as well as config code) for an interface if the interface happens to be rejected.
if(not $problem_lines) { $target_lines .= <$html_desc_prefix$html_if_title_desc -- $sysname
ECHO $target_lines .= < ECHO $target_lines .= < ECHO $target_lines .= < ECHO $target_lines .= < ECHO } else { $head_lines=""; $problem_lines=""; $target_lines=""; $separator_lines=""; }
Template Example 2: Simplier Version of Example 1
Example 1 was partly intended to demonstrate how to customize the generation of interface targets but also to provide a hint of how the variables are used in the default template which one could consider that cfgmaker normally uses.
If you‘re only intrested in the easiest way of entirely eliminating those reject interfaces, the template below would do the job as well by using $default_target_lines.
if($if_ok) { $target_lines = $default_target_lines; } else { $head_lines=""; $problem_lines=""; $target_lines=""; $separator_lines=""; }
Template Example 3: Creating CPU Targets for Hosts
Below is an example of a host template.:
$head_lines .= <$router_name CPU load
System: $sysname in $html_syslocation
Maintainer: $html_syscontact
Description: $html_if_description
ifType: $html_if_type_desc ($if_type_num)
ifName: $html_if_snmp_name
Port Name: $if_port_name
Max Speed: $if_speed_str
Ip: $if_ip ($if_dns_name)
System: $router_name in $html_syslocation
Maintainer: $html_syscontact
Description: $html_sysdescr
Resource: CPU.
ECHO
实例
The first example creates a config file for router.place.xyz: the router has the community name public. Interfaces get identified by their IP number. Two global options get added to the config file. The config file gets redirected to mrtg.conf. The ‘‘ signs at the end of the line mean that this command should be written on a single line.
cfgmaker --global "WorkDir: /home/tobi" --global "Options[_]: growright,bits" --ifref=ip public@router.place.xyz > mrtg.cfg Note:
if cfgmaker is not in your path, but you are in the directory where cfgmaker is stored, you can start it with ./cfgmaker
The next example creates a config file for four devices: router1.place.xyz, router2.place.xyz, switch1.place.xyz and switch2.place.xyz all with the community public.
The two routers will have --ifref set to descr whilst the two switches will use --ifref set to name. Further the routers will use --ifdesc set to alias and switch1.place.xyz will use --ifdesc set to descr whilst switch2.place.xyz use name instead.
Finally, there will be two Options lines inserted in the configuration: One will be in the beginning, whilst the other will be inserted after the lines related to the two routers but before those lines related to the switches.
cfgmaker --global "WorkDir: /home/tobi" --global "Options[_]: growright,bits" --ifref=descr --ifdesc=alias public@router1.place.xyz public@router2.place.xyz --global "Options[_]: growright" --ifref=name --ifdesc=descr public@switch1.place.xyz --ifdesc=name public@switch2.place.xyz > mrtg.cfg
The next example demonstrates how to use the --community, --snmp-options and --dns-domain to make the command line simpler. All the equipment will use the community hidden, except for the ppp-server which use community access. All equipment uses these SNMP options: 1s timeout, 1 retry and SNMP version 2 (backoff and port is unspecified which means they use the default values). The exception again is the ppp-server which uses SNMP version 1. Finally, all the equipment is part of the domain place.xyz, except for the ppp-server which is part of the domain remote.place.xyz. Note that the latter is achieved simply by specifying the name of the ppp-server to be ppp-server.remote .
cfgmaker --global "WorkDir: /home/tobi" --global "Options[_]: growright,bits" --dns-domain=place.xyz --community=hidden --snmp-options=::1:1::2 router1 router2 router3 router4 router5 switch1 switch2 switch3 switch4 switch5 switch6 switch7 access@ppp-server.remote:::::1 > mrtg.cfg
MRTG的index文件生成工具
indexmaker为web站点创建index文件。
NAME
SYNOPSIS
OPTIONS
DESCRIPTION
NAME
indexmaker - Creates index files for mrtg web sites (mrtg-2.12.2)
SYNOPSIS
indexmaker [options] mrtg.cfg [other.cfg ...]
OPTIONS
--output=filename
set output filename (default: stdout)
--filter title=~regexp select targets by matching regexp against titles --filter pagetop=~regexp select targets by matching regexp against pagetop --filter name=~regexp select targets by matchin regexp against name
--addhead=text insert this text between and
--title=text set title of generated index file
--subtitle=text
add a subtitle to the generated index file
--bodyopt=text set body tag options
--headlevel=number
use at top of page (default: 1)
--pagetop=text insert this text between and

...


--pageend=text insert this text after the main body
--pagetopend=text
use this text for pagetop or pageend if undefined
--nolegend do not add the Mrtg legend at the end of the page
--columns=number
show graphs in a table with x columns (default: 2)
--perhost show graphs of the same host on a row
--compact try to make a vertically more compact page
--optlog log the used command line in the page (default: log)
--sort=title sort graphs by title
--sort=name sort graphs by their name
--sort=descr sort graphs by their description
--sort=original
leave as is (default)
--enumerate add a sequence number to the title of each graph
--picfirst place pictures before text (default: text first)
--width=number set width of graphs (default: not set)
System Message: WARNING/2 (, line 46)
Option list ends without a blank line; unexpected unindent.
--height=number --sidebyside place text / pictures side by side (default: above/below) --bold use bold text (default: bold) --clicktext make the text link to the inner page (like the image)
--show=day pick which graph to show in the index (default)
System Message: WARNING/2 (, line 52)
Option list ends without a blank line; unexpected unindent.
--show=week --show=month --show=year --show=none
--section=h1 h1 tag from pagetop as section heading (default)
--section=title
title as section headings for graphs
--section=name graph name as section heading
--section=descr
graph description as section heading
--section=portname
port name entry in pagetop as section heading
--sectionhost Try to prepend the host to the section heading if missing
--rrdviewer=path
path to rrdviewer (default: /cgi-bin/14all.cgi)
--icondir=path path to icondir
--prefix=path path from the location of the index.html to the graphs
--headeradd=string
add string to the html page header
--autoprefix try to set prefix automatically
-file=file read string argument for option from file
DESCRIPTION
Indexmaker can create web pages which display the status of an array of mrtg interface status pages.
--output filename
set output filename (default: stdout)
--filter (title|pagetop|name)(=~|!~)regexp
Several filters may get set. Each filter can match agains the contents of a specific section of the mrtg config file. Name refers to the bit in square brackets (option[name]: bla).
Depending on the match operator chosen (=~ or !~) the match will be positive or negative.
Note that some shells consider ! a special character. It may be necessary to type !~ instead.
--title text Set title of generated index file (default: regexp)
--bodyopt text
The value of this argument gets appended to the tag. This allows to set document colors. By default this option is set to
bgcolor="#ffffff" text="#000000" link="#000000" vlink="#000000" alink="#000000"
--columns number
Display graphs in a table with number columns (default: 2)
--sort title|name|descr|original
Sort the graphs in the page either by title, by name, by interface description, or leave them as is.
--enumerate Add a sequence number to the title of each graph
--width number Set width of graphs
--height number
Set the height of the graphs
--show day|week|month|year|none
Select which graph to show in the index page. You can supress images completely with --show=none.
--section h1|title|name|description|portname
Select what to use as the title for each graph in the page. h1 is the H1 section from pagetop, title is the graph title, name is the bit in square brackets (option[name]: bla), and descr or description is the text from the Description field of the PageTop (the Cisco description text if it‘s available, otherwise just the interface description). portname is the Port Name: from pagetop.
--sectionhost Extract the hostname from the target line (this does not work if the target is a mathematial expression). Prepend the hostname (and a colon) to the section if not already present.
--rrdviewer path
If you have set the LogFormat: rrdtool property in the mrtg.cfg file, the index will take this into account. The only thing you must tell it is the path to your grapher cgi. (default: /cgi-bin/14all.cgi)
--prefix path By default we assume that the file generated by indexmaker is stored in WorkDir. If you want to store it somewhere else, specify how to reach WorkDir from the place where the Index is stored. Note that you have to use ‘/‘ as path separator as this will be used in urls. Speaking of which, you can even enter a whole url.
--autoprefix path
Requires --output. Try to generate the prefix automatically by comparision of the path to the output file set with --output and the Htmldir set in the configuration files. Particulary useful when multiple configuration files are specified, with different Htmldir settings.
--optlog Default is logging in the generated page the command line, suppress with --nooptlog . Useful if the commandline contains a complex --pagetop=string which could confuse simple browsers.
--someoption-file filename
For any someoption which takes a string as parameter you can read the string from a file by adding <-file> to the option keyword. The whole content of the file will be read and used as the string. The file must exist.
mrtg的配置参考指南
mrtg的配置参考指南
NAME
OVERVIEW
SYNTAX
GLOBAL KEYWORDS
OPTIONAL GLOBAL KEYWORDS
EXAMPLES
NAME
mrtg-reference - MRTG 2.12.2 configuration reference
OVERVIEW
The runtime behaviour of MRTG is governed by a configuration file. Run-of- ther-mill configuration files can be generated with cfgmaker. (Check the cfgmaker manpage). But for more elaborate configurations some hand-tuning is required.
This document describes all the configuration options understood by the mrtg software.
SYNTAX
MRTG configuration file syntax follows some simple rules:
Keywords must start at the beginning of a line.
Lines which follow a keyword line which start with a blank are appended to the keyword line
Empty Lines are ignored
Lines starting with a # sign are comments.
You can add other files into the configuration file using:
Include: file
Example:
Include: base-options.inc
If included files are specified with relative paths, both the current working directory and the directory containing the main config file will be searched for the files.
GLOBAL KEYWORDS
WorkDir
WorkDir specifies where the logfiles and the webpages should be created.
Example:
WorkDir: /usr/tardis/pub/www/stats/mrtg
OPTIONAL GLOBAL KEYWORDS
HtmlDir
HtmlDir specifies the directory where the html (or shtml, but we‘ll get on to those later) lives.
NOTE: Workdir overrides the settings for htmldir, imagedir and logdir.
Example:
Htmldir: /www/mrtg/
ImageDir
ImageDir specifies the directory where the images live. They should be under the html directory.
Example:
Imagedir: /www/mrtg/images
LogDir
LogDir specifies the directory where the logs are stored. This need not be under htmldir directive.
Example:
Logdir: /www/mrtg/logs
Forks (UNIX only)
With system that supports fork (UNIX for example), mrtg can fork itself into multiple instances while it is acquiring data via snmp.
For situations with high latency or a great number of devices this will speed things up considerably. It will not make things faster, though, if you query a single switch sitting next door.
As far as I know NT can not fork so this option is not available on NT.
Example:
Forks: 4
EnableIPv6
When set to yes, IPv6 support is enabled if the required libraries are present (see the the mrtg-ipv6 manpage manpage). When IPv6 is enabled, mrtg can talk to routers using SNMP over IPv6 and targets may be specified by their numeric IPv6 addresses as well as by hostname or IPv4 address.
If IPv6 is enabled and the target is a hostname, mrtg will try to resolve the hostname to an IPv6 address and, if this fails, to an IPv4 address. Note that mrtg will only use IPv4 if you specify an IPv4 address or a hostname with no corresponding IPv6 address; it will not fall back to IPv4 if it simply fails to communicate with the target using IPv6. This is by design.
Note that many routers do not currently support SNMP over IPv6. Use the IPv4Only per target option for these routers.
IPv6 is disabled by default.
Example:
EnableIPv6: Yes
Refresh
How many seconds apart should the browser (Netscape) be instructed to reload the page? If this is not defined, the default is 300 seconds (5 minutes).
Example:
Refresh: 600
Interval
How often do you call mrtg? The default is 5 minutes. If you call it less often, you should specify it here. This does two things:
The generated HTML page contains the right information about the calling interval ...
A META header in the generated HTML page will instruct caches about the time-to-live of this page .....
In this example, we tell mrtg that we will be calling it every 10 minutes. If you are calling mrtg every 5 minutes, you can leave this line commented out.
Example:
Interval: 10
Note that unless you are using rrdtool you can not set Interval to less than 5 minutes. If you are using rrdtool you can set interval down to 1 minute. Note though, setting the Interval for an rrdtool/mrtg setup will influence the initial creation of the database. If you change the interval later, all existing databases will remain at the resolution they were initially created with.
MaxAge
MRTG relies heavily on the real time clock of your computer. If the time is set to a wrong value, especially if it is advanced far into the future, this will cause mrtg to expire lots of supposedly old data from the log files.
To prevent this, you can add a ‘reasonability‘ check by specifying a maximum age for log files. If a file seems to be older, mrtg will not touch it but complain instead, giving you a chance to investigate the cause.
Example:
MaxAge: 7200
The example above will make mrtg refuse to update log files older than 2 hours (7200 seconds).
WriteExpires
With this switch mrtg will generate .meta files for CERN and Apache servers which contain Expiration tags for the html and gif files. The*.meta files will be created in the same directory as the other files, so you will have to set``MetaDir .‘‘ and``MetaFiles on‘‘ in your apache.conf or .htaccess file for this to work
System Message: (, line 141);backlink
Inline emphasis start-string without end-string.
System Message: (, line 141);backlink
Inline literal start-string without end-string.
System Message: (, line 141);backlink
Inline literal start-string without end-string.
NOTE: If you are running Apache-1.2 or later, you can use the mod_expire to achieve the same effect ... see the file htaccess.txt
Example:
WriteExpires: Yes
NoMib2
Normally we ask the SNMP device for ‘sysUptime‘ and ‘sysName‘ properties. Some do not have these. If you want to avoid getting complaints from mrtg about these missing properties, specify the nomib2 option.
An example of agents which do not implement base mib2 attributes are Computer Associates - Unicenter TNG Agents. CA relies on using the base OS SNMP agent in addition to its own agents to supplement the management of a system.
Example:
NoMib2: Yes
SingleRequest
Some SNMP implementations can not deal with requests asking for multiple snmp variables in one go. Set this in your cfg file to force mrtg to only ask for one variable per request.
Examples
SingleRequest: Yes
SnmpOptions
Apart from the per target timeout options, you can also configure the behaviour of the snmpget process on a more profound level. SnmpOptions accepts a hash of options. The following options are currently supported:
timeout => $default_timeout, retries => $default_retries, backoff => $default_backoff, default_max_repetitions => $max_repetitions, use_16bit_request_ids => 1, lenient_source_port_matching => 0, lenient_source_address_matching => 1
The values behind the options indicate the current default value. Note that these settings OVERRIDE the per target timeout settings.
The 16bit request ids are the only way to query the broken SNMP implementation of SMC Barricade routers.
Example:
SnmpOptions: retries => 2, only_ip_address_matching => 0
Note that AS/400 snmp seems to be broken in a way which prevents mrtg from working with it unless
SnmpOptions: lenient_source_port_matching => 1
is set.
IconDir
If you want to keep the mrtg icons in someplace other than the working (or imagedir) directory, use the IconDir variable for defining the url of the icons directory.
Example:
IconDir: /mrtgicons/
LoadMIBs
Load the MIB file(s) specified and make its OIDs available as symbolic names. For better efficiancy, a cache of MIBs is maintained in the WorkDir.
Example:
LoadMIBs: /dept/net/mibs/netapp.mib,/usr/local/lib/ft100m.mib
Language
Switch output format to the selected Language (Check the translate directory to see which languages are supported at the moment. In this directory you can also find instructions on how to create new translations).
Currently the following laguages are supported:
big5 brazilian bulgarian catalan chinese croatian czech danish dutch eucjp french galician gb gb2312 german greek hungarian icelandic indonesia iso2022jp italian korean lithuanian malay norwegian polish portuguese romanian russian russian1251 serbian slovak slovenian spanish swedish turkish ukrainian
Example:
Language: danish
LogFormat
Setting LogFormat to ‘rrdtool‘ in your mrtg.cfg file enables rrdtool mode. In rrdtool mode, mrtg relies on rrdtool to do its logging. See the mrtg-rrd manpage.
Example:
LogFormat: rrdtool
LibAdd
If you are using rrdtool mode and your rrdtool Perl module (RRDs.pm) is not installed in a location where perl can find it on its own, you can use LibAdd to supply an appropriate path.
Example:
LibAdd: /usr/local/rrdtool/lib/perl/
PathAdd
If the rrdtool executable can not be found in the normal PATH, you can use this keyword to add a suitable directory to your path.
Example:
PathAdd: /usr/local/rrdtool/bin/
RunAsDaemon
The RunAsDaemon keyword enables daemon mode operation. The purpose of daemon mode is that MRTG is launched once and not repeatedly (as it is with cron). This behavior saves computing resourses as loading and parsing of configuration files happens only once.
Using daemon mode MRTG itself is responible for timing the measurement intervals. Therfore its important to set the Interval keyword to an apropiate value.
Note that when using daemon mode MRTG should no longer be started from cron as each new process runs forever. Instead MRTG should be started from the command prompt or by a system startup script.
If you want mrtg to run under a particular user and group (it is not recomended to run MRTG as root) then you can use the --user=user_name and --group=group_name options on the mrtg commandline.
mrtg --user=mrtg_user --group=mrtg_group mrtg.cfg
Also note that in daemon mode restarting the process is required in order to activate changes in the config file.
Under UNIX, the Daemon switch causes mrtg to fork into background after checking its config file. On Windows NT the MRTG process will detach from the console, but because the NT/2000 shell waits for its children you have to use this special start sequence when you launch the program:
start /b perl mrtg mrtg.cfg
You may have to add path information equal to what you add when you run mrtg from the commandline.
Example
RunAsDaemon: Yes Interval: 5
This makes MRTG run as a daemon beginning data collection every 5 minutes
If you are daemontools and still want to run mrtg as a daemon you can additionally specify
NoDetach: Yes
this will make mrtg run but without detaching it from the terminal.
ConversionCode
Some devices may produce non-numeric values that would nevertheless be useful to graph with MRTG if those values could be converted to numbers. The ConversionCode keyword specifies the path to a file containing Perl code to perform such conversions. The code in this file must consist of one or more Perl subroutines. Each subroutine must accept a single string argument and return a single numeric value. When RRDtool is in use, a decimal value may be returned. When the name of one of these subroutines is specified in a target definition (see below), MRTG calls it twice for that target, once to convert the the input value being monitored and a second time to convert the output value. The subroutine must return an undefined value if the conversion fails. In case of failure, a warning may be posted to the MRTG log file using Perl‘s warn function. MRTG imports the subroutines into a separate name space (package MRTGConversion), so the user need not worry about pollution of MRTG‘s global name space. MRTG automatically prepends this package declaration to the user-supplied code.
Example: Suppose a particular OID returns a character string whose length is proportional to the value to be monitored. To convert this string to a number that can be graphed by MRTG, create a file arbitrarily named``MyConversions.pl‘‘ containing the following code:
System Message: (, line 282);backlink
Inline literal start-string without end-string.
# Return the length of the string argument sub Length2Int {
System Message: ERROR/3 (, line 286)
Unexpected indentation.
my $value = shift; return length( $value );
System Message: WARNING/2 (, line 288)
Block quote ends without a blank line; unexpected unindent.
System Message: INFO/1 (, line 288)
Unexpected possible title overline or transition. Treating it as ordinary text because it‘s so short.
}
Then include the following global keyword in the MRTG configuration file (assuming that the conversion code file is saved in the mrtg/bin directory along with mrtg itself):
ConversionCode: MyConversions.pl
This will cause MRTG to include the definition of the subroutine Length2Int in its execution environment. Length2Int can then be invoked on any target by appending``|Length2Int‘‘ to the target definition as follows:
System Message: (, line 294);backlink
Inline literal start-string without end-string.
System Message: (, line 294);backlink
Inline substitution_reference start-string without end-string.
Target[myrouter]: 1.3.6.1.4.1.999.1&1.3.6.1.4.1.999.1:public@mydevice|Length2Int
See``Extended Host Name Syntax‘‘ below for complete target definition syntax information.
System Message: (, line 298);backlink
Inline literal start-string without end-string.
PER TARGET CONFIGURATION
Each monitoring target must be identified by a unique name. This name must be appended to each parameter belonging to the same target. The name will also be used for naming the generated webpages, logfiles and images for this target.
Target
With the Target keyword you tell mrtg what it should monitor. The Target keyword takes arguments in a wide range of formats:
Basic
The most basic format is``port:community@router‘‘ This will generate a traffic graph for the interface ‘port‘ of the host ‘router‘ (dns name or IP address) and it will use the community ‘community‘ (snmp password) for the snmp query.
System Message: (, line 309);backlink
Inline literal start-string without end-string.
Example:
Target[myrouter]: 2:public@wellfleet-fddi.ethz.ch
If your community contains a``@‘‘ or a `` ‘‘ these characters must be escaped with a``‘‘.
System Message: (, line 315);backlink
Inline literal start-string without end-string.
System Message: (, line 315);backlink
Inline literal start-string without end-string.
Target[bla]: 2:stupi@d@router
SNMPv2c
If you have a fast router you might want to try to poll the ifHC* counters. This feature gets activated by switching to SNMPv2c. Unfortunately not all devices support SNMPv2c yet. If it works, this will prevent your counters from wraping within the 5 minute polling interval, since we now use 64 bit instead of the normal 32 bit.
Example:
Target[myrouter]: 2:public@router1:::::2
Reversing
Sometimes you are sitting on the wrong side of the link, and you would like to have mrtg report Incoming traffic as Outgoing and vice versa. This can be achieved by adding the ‘-‘ sign in front of the``Target‘‘ description. It flips the incoming and outgoing traffic rates.
System Message: (, line 327);backlink
Inline literal start-string without end-string.
Example:
Target[ezci]: -1:public@ezci-ether.ethz.ch
Explicit OIDs
You can also explicitly define which OID to query by using the following syntax ‘OID_1&OID_2:community@router‘ The following example will retrieve error counts for input and output on interface 1. MRTG needs to graph two variables, so you need to specify two OID‘s such as temperature and humidity or error input and error output.
Example:
Target[myrouter]: 1.3.6.1.2.1.2.2.1.14.1&1.3.6.1.2.1.2.2.1.20.1:public@myrouter
MIB Variables
MRTG knows a number of symbolic SNMP variable names. See the file mibhelp.txt for a list of known names. One example are the ifInErrors and ifOutErrors. This means you can specify the above as:
Example:
Target[myrouter]: ifInErrors.1&ifOutErrors.1:public@myrouter
Interface by IP
Sometimes SNMP interface index can change, like when new interfaces are added or removed. This can cause all Target entries in your config file to become offset, causing MRTG to graphs wrong instances etc. MRTG supports IP address instead of ifindex in target definition. Then MRTG will query snmp device and try to map IP address to the current ifindex. You can use IP addresses in every type of target definition by adding IP address of the numbered interface after OID and separation char ‘/‘.
Make sure that the given IP address is used on your same target router, especially when graphing two different OIDs and/or interface split by ‘&‘ delimiter.
You can tell cfgmaker to generate such references with the option --ifref=ip.
Example:
Target[myrouter]: /1.2.3.4:public@wellfleet-fddi.ethz.ch Target[ezci]: -/1.2.3.4:public@ezci-ether.ethz.ch Target[myrouter]: 1.3.6.1.2.1.2.2.1.14/1.2.3.4&1.3.6.1.2.1.2.2.1.14/1.2.3.4:public@myrouter Target[myrouter]: ifInErrors/1.2.3.4&ifOutErrors/1.2.3.4:public@myrouter
Interface by Description
If you can not use IP addresses you might want to use the interface names. This works similar to the IP address aproach except that the prefix to use is a instead of a /
You can tell cfgmaker to generate such references with the option --ifref=descr.
Example:
Target[myrouter]: My-Interface2:public@wellfleet-fddi.ethz.ch Target[ezci]: -My-Interface2:public@ezci-ether.ethz.ch Target[myrouter]: 1.3.6.1.2.1.2.2.1.14My-Interface2&1.3.6.1.2.1.2.2.1.14My-Interface3:public@myrouter Target[myrouter]: ifInErrorsMy-Interface2&ifOutErrorsMy-Interface3:public@myrouter
If your description contains a``&‘‘, a``:‘‘, a``@‘‘ or a `` ‘‘ you can include them but you must escape with a backlash:
System Message: (, line 373);backlink
Inline literal start-string without end-string.
System Message: (, line 373);backlink
Inline literal start-string without end-string.
System Message: (, line 373);backlink
Inline literal start-string without end-string.
Target[myrouter]: fun:ney&ddd:public@hello.router
Interface by Name
This is the only sensible way to reference the interfaces of your switches.
You can tell cfgmaker to generate such references with the option --ifref=name.
Example:
Target[myrouter]: #2/11:public@wellfleet-fddi.ethz.ch Target[ezci]: -#2/11:public@ezci-ether.ethz.ch Target[myrouter]: 1.3.6.1.2.1.2.2.1.14#3/7&1.3.6.1.2.1.2.2.1.14#3/7:public@myrouter Target[myrouter]: ifInErrors#3/7&ifOutErrors#3/7:public@myrouter
If your description contains a``&‘‘, a``:‘‘, a``@‘‘ or a `` ‘‘ you can include them but you must escape with a backlash:
System Message: (, line 389);backlink
Inline literal start-string without end-string.
System Message: (, line 389);backlink
Inline literal start-string without end-string.
System Message: (, line 389);backlink
Inline literal start-string without end-string.
Target[myrouter]: #:fun:public@hello.router

Interface by Ethernet Address
When the SNMP interface index changes, you can key that interface by its ‘Physical Address‘, sometimes called a ‘hard address‘, which is the SNMP variable ‘ifPhysAddress‘. Internally, MRTG matches the Physical Address from the*.cfg file to its current index, and then uses that index for the rest of the session.
System Message: (, line 396);backlink
Inline emphasis start-string without end-string.
You can use the Physical Address in every type of target definition by adding the Physical Address after the OID and the separation char ‘!‘ (analogous to the IP address option). The Physical address is specified as ‘-‘ delimited octets, such as``0a-0-f1-5-23-18‘‘ (omit the double quotes). Note that some routers use the same Hardware Ethernet Address for all of their Interfaces which prevents unique interface identification. Mrtg will notice such problems and alert you.
System Message: (, line 398);backlink
Inline literal start-string without end-string.
You can tell cfgmaker to generate configuration files with hardware ethernet address references by using the option --ifref=eth.
Example:
Target[myrouter]: !0a-0b-0c-0d:public@wellfleet-fddi.ethz.ch Target[ezci]: -!0-f-bb-05-71-22:public@ezci-ether.ethz.ch Target[myrouter]: 1.3.6.1.2.1.2.2.1.14!0a-00-10-23-44-51&!0a-00-10-23-44-51:public@myrouter Target[myrouter]: ifInErrors!0a-00-10-23-44-51&ifOutErrors!0a-00-10-23-44-51:public@myrouter
Interface by Type
It seems that there are devices that try to defy all monitoring efforts: the interesting interfaces have neither ifName nor a constant ifDescr not to mention a persistant ifIndex. The only way to get a constant mapping is by looking at the interface type, because the interface you are interested in is unique in the device you are looking at ...
You can tell cfgmaker to generate such references with the option --ifref=type.
Example:
Target[myrouter]: %13:public@wellfleet-fddi.ethz.ch Target[ezci]: -%13:public@ezci-ether.ethz.ch Target[myrouter]: 1.3.6.1.2.1.2.2.1.14%13&1.3.6.1.2.1.2.2.1.14%14:public@myrouter Target[myrouter]: ifInErrors%13&ifOutErrors%14:public@myrouter
Extended Host Name Syntax
In all places where``community@router‘‘ is accepted, you can add additional parameters for the SNMP communication using colon-separated suffixes. You can also append a pipe symbol ( | ) and the name of a numeric conversion subroutine as described under the global keyword``ConversionCode‘‘ above. The full syntax is as follows:
System Message: (, line 422);backlink
Inline literal start-string without end-string.
System Message: (, line 422);backlink
Inline literal start-string without end-string.
community@router[:[port][:[timeout][:[retries][:[backoff][:[version]][|name]]]]]
System Message: (, line 424);backlink
Inline substitution_reference start-string without end-string.
where the meaning of each parameter is as follows:
port
the UDP port under which to contact the SNMP agent (default: 161)
timeout
initial timeout for SNMP queries, in seconds (default: 2.0)
retries
number of times a timed-out request will be retried (default: 5)
backoff
factor by which the timeout is multiplied on every retry (default: 1.0).
version
for SNMP version. If you have a fast router you might want to put a ‘2‘ here. This will make mrtg try to poll the 64 bit counters and thus prevent excessive counter wrapping. Not all routers support this though.
Example:
3:public@router1:::::2
name
the name of the subroutine that MRTG will call to convert the input and output values to integers. See the complete example under the global keyword``ConversionCode‘‘ above.
System Message: (, line 448);backlink
Inline literal start-string without end-string.
Example:
1.3.6.1.4.1.999.1&1.3.6.1.4.1.999.2:public@mydevice:161::::2|Length2Int
This would retrieve values from the OID 1.3.6.1.4.1.999.1 for input and .2 for output on mydevice using UDP port 161 and SNMP version 2, and would execute the user-defined numeric conversion subroutine Length2Int to convert those values to integers.
A value that equals the default value can be omitted. Trailing colons can be omitted, too. The pipe symbol followed by the name parameter, if present, must come at the end. There must be no spaces around the colons or pipe symbol.
Example:
Target[ezci]: 1:public@ezci-ether.ethz.ch:9161::4
This would refer to the input/output octet counters for the interface with ifIndex 1 on ezci-ether.ethz.ch, as known by the SNMP agent listening on UDP port 9161. The standard initial timeout (2.0 seconds) is used, but the number of retries is set to four. The backoff value is the default. Numeric IPv6 addresses
System Message: ERROR/3 (, line 464)
Unexpected indentation.
If IPv6 is enabled you may also specify a target using its IPv6 address. To avoid ambiguity with the port number, numeric IPv6 addresses must be placed in square brackets.
Example:
Target[IPv6test]: 2:public@[2001:760:4::]:6161::4
External Monitoring Scripts
If you want to monitor something which does not provide data via snmp you can use some external program to do the data gathering.
The external command must return 4 lines of output:
Line 1
current state of the first variable, normally ‘incoming bytes count‘
Line 2
current state of the second variable, normally ‘outgoing bytes count‘
Line 3
string (in any human readable format), telling the uptime of the target.
Line 4
string, telling the name of the target.
Depending on the type of data your script returns you might want to use the ‘gauge‘ or ‘absolute‘ arguments for the Options keyword.
Example:
Target[myrouter]: /usr/local/bin/df2mrtg /dev/dsk/c0t2d0s0
Note the use of the backticks (`), not apostrophes (‘) around the command.
If you want to use a backtick in the command name this can be done but you must escape it with a backslash ...
If your script does not have any data to return but does not want mrtg to complain about invalid data, it can return ‘UNKNOWN‘ instead of a number. Note though that only rrdtool is realy equipped to handle unknown data well. Multi Target Syntax
System Message: ERROR/3 (, line 499)
Unexpected indentation.
You can also combine several target definitions in a mathematical expression. Any syntactically correct expression that the Perl interpreter can evaluate to will work. An expression could be used, for example, to aggregate both B channels in an ISDN connection or to calculate the percentage hard disk utilization of a server from the a