Mrtg

#2 Мониторинг использования диска

Допустим, что нам нужно наблюдать скорости чтения и записи на софтверный RAID-массив md0. Количество считанных и записанных байт можно узнать из вывода команды iostat, а скорости можно получить, наблюдая изменения этих величин с течением времени.

Для начала создадим скрипт /root/scripts/mrtgstat_iostat.sh следующего содержания:

#!/bin/sh

# Этому скрипту в качестве первого параметра передаётся имя устройства,
# данные о котором необходимо получить

# Если имя устройства передано
if ; then
    # Получаем строку с информацией по устройству
    DATA=`iostat -k ${1} | tail -n 2 | head -n 1`
    # Отображаем количество записанных байт
    echo ${DATA} | awk '{ print $6; }'
    # Отображаем количество считанных байт
    echo ${DATA} | awk '{ print $5; }'
    # Отображаем временную метку в формате юникс
    date +%s
    # Отображаем имя хоста
    hostname
fi

Далее добавляем в конфигурацию MRTG строки:

Target: `/root/scripts/mrtgstat_iostat.sh md0`
MaxBytes: 1
Title: md0 r/w statistics
PageTop: <h1>md0 r/w statistics</h1>
AbsMax: 1250000
Options: integer,nopercent,nobanner
YLegend: kilobytes per second
ShortLegend: kbps
Legend1: Read kilobytes per second
Legend2: Write kilobytes per second

Получаемый график будет выглядеть примерно вот так:

Планы по MRTG-3

Сбор данных по SNMP

RRD сдвигает узкое место производительности MRTG к компоненту по сбору данных. План по увеличению производительности сбора SNMP-данных сводится к параллельной обработке SNMP-запросов. Это зависит от задержек в сети и того, что роутеры медленно отвечают на SNMP-запросы.

Графики по требованию

Так как генерация графиков – затратная операция, то нет смысле генерировать тысячи gif-изображений для каждой операции обновления. Гораздо выгоднее генерировать графики только, когда пользователь хочет их увидеть. График, показанный на рис. 6, генерируется около 0.3 секунд на Pentium 120. Это значит, что графики могут создаваться на лету и может быть достигнуто приемлимое время ответа от сервера. Для высоконагруженных сайтов может быть настроен графический кэш, так, чтобы графики регенерировались, только когда они устарели.

Генерация HTML

В MRTG-2 генерация HTML страниц была реализована с использованием большого количества опций. MRTG-3 будет работать с файлами шаблонов и поэтому сделает дизайн страниц HTML более простым и гибким.

Конфигурация

MRTG-2 была монолитным приложением, а MRTG-3 – набор Perl-модулей, которые могут быть собраны в одно приложение для мониторинга. Пользователь может решать, какие модули использовать.
Один модуль будет предлагать высокоуровневый пользовательский интерфейс для создания приложений по аналогии с MRTG-2. Скрипты, которые использует этот модуль, состоят из двух частей. Первая, в которой пользователь определяет все источники данных для мониторинга. Вторая часть представляет из себя обработчик событий, который собирает и обрабатывает данные и обновляет соответствующие RRD и HTML-страницы в указанном порядке.

Community Properties

Sub-menu:

This sub-menu allows to set up access rights for the SNMP data.

There is little security in v1 and v2c, just Clear text community string („username“) and ability for Limiting access by IP adress.

In production environment SNMP v3 should be used as that provides security — Authorisation (User + Pass) with MD5/SHA1, Encryption with DES (and since v6.16, AES).


 /snmp community> print value-list 
                     name: public
                  address: 0.0.0.0/0
                 security: none
              read-access: yes
             write-access: no
  authentication-protocol: MD5
      encryption-protocol: DES
  authentication-password: *****
      encryption-password: *****

Warning: Default settings only have one community named public without any additional security settings. These settings should be considered insecure and should be adjusted according required security profile.

Properties

Property Description
address (IP/IPv6 address; Default: 0.0.0.0/0) Addresses from which connections to SNMP server is allowed
authentication-password (string; Default: «») Password used to authenticate connection to the server (SNMPv3)
authentication-protocol (MD5 | SHA1; Default: MD5) Protocol used for authentication (SNMPv3)
encryption-password (string; Default: «») password used for encryption (SNMPv3)
encryption-protocol (DES | AES; Default: DES) encryption protocol to be used to encrypt the communication (SNMPv3). AES (see rfc3826) available since v6.16.
name (string; Default: )
read-access (yes | no; Default: yes) Whether read access is enabled for this community
security (authorized | none | private; Default: none)
write-access (yes | no; Default: no) Whether write access is enabled for this community.

Установка MRTG 2.17.2 (snmp) за 5 минут под Windows 7

Понадобилось мониторить на циске один из интерфейсов, до этого везде активно использовал Cacti, но тут задача была проще и не было под рукой линукса, нужно было решение чтобы в короткий срок получить график загрузки интерфейса на рабочем компе с Windows 7, на помощь пришла утилита MRTG.

Скачиваем MRTG 2.17.2 с официального сайта (http://oss.oetiker.ch), распаковываем на диск С:\. Скачиваем и устанавливаем perl, я установил Strawberry Perl.

Пуск -> Компьютер -> Свойства системы -> Дополнительные параметры системы -> Переменные среды -> Системные переменные -> Создать

Имя переменной: perl значение переменной: C:\Perl\bin;%SystemRoot%\system32;%SystemRoot%;

cd c:\mrtg-2.17.2\bin c:\mrtg-2.17.2\bin\perl mrtg

Если появилось сообщение что нет конфигурационного файла, то все хорошо, сгенерим его: . Не забываем прописать доступ (SNMP) для нашего компа на оборудовании, с которого хотим получить информацию.

perl cfgmaker public@192.168.0.20 —global «WorkDir: c:\mrtg» —output mrtg.cfg

Это может занять какое-то время, в моем случае выдергивал с cisco 3560G-48, в результате в c:\mrtg-2.17.2\bin\ получаем: mrtg.cfg

Можно конфиг подредактировать, если вам нужны не все интерфейсы.

В конфигурационном файле проверить, должна присутствовать строка:

в этой папке будут генериться .html файлы с графиками .png

Запуск опроса оборудования делается следующим образом c:\mrtg-2.17.2\bin\perl mrtg mrtg.cfg

В первые запуски будут выдаваться ошибки, это нормально, так как файлов еще нет.

Чтобы вручную не запускать опрос, можно запустить в режиме демона, для этого в конфигурационный файл добавляем строчку:

c:\mrtg-2.17.2\bin\perl mrtg mrtg.cfg

Опрос будет проводиться автоматически каждые 5 минут, единственное нельзя закрывать окно.

источник

Meaning of Help configuring MRTG on Ubuntu 8.04?

Help configuring MRTG on Ubuntu 8.04 is the error name that contains the details of the error, including why it occurred, which system component or application malfunctioned to cause this error along with some other information. The numerical code in the error name contains data that can be deciphered by the manufacturer of the component or application that malfunctioned. The error using this code may occur in many different locations within the system, so even though it carries some details in its name, it is still difficult for a user to pinpoint and fix the error cause without specific technical knowledge or appropriate software.

#3 Мониторинг времени отклика хоста

Достаточно хорошей характеристикой канала в Интернет является время отклика от некоего хоста с заведомо быстрым откликом.

Наблюдать за качеством канала можно, производя периодические замеры времени отклика. Попробуем нарисовать графики максимального и минимального времени отклика заданного хоста в зависимости от времени.

В Debian-based дистрибутивах (в том числе и в Ubuntu) присутствует готовый скрипт для этой задачи, он находится в пакете mrtg-ping-probe, установим его:

apt-get install mrtg-ping-probe

При вызове скрипта нужно указать имя хоста. По умолчанию будет сделано десять попыток и потом выбрано минимальное и максимальное время отклика. Если количество попыток нужно изменить то можно использовать ключ -k.

Добавим в конфигурацию MRTG строки:

Target: `/usr/bin/mrtg-ping-probe -k 3 ylsoftware.com.`
SetEnv: MRTG_INT_IP="ylsoftware.com" MRTG_INT_DESCR="ping"
Title: Ping of ylsoftware VPS
MaxBytes: 1000
AbsMax: 3000
Options: gauge,nobanner
YLegend: ping time (ms)
ShortLegend: ms
Legend1: Maximum Round Trip Time in ms
Legend2: Minimum Round Trip Time in ms
Legend3: Maximal 5 Minute Maximum Round Trip Time in ms
Legend4: Maximal 5 Minute Minimum Round Trip Time in ms
LegendI: &nbsp;Max:
LegendO: &nbsp;Min:

Полученный график будет иметь вид:

SNMP write

Since RouterOS v3, SNMP write is supported for some functions. SNMP write allows to change router configuration with SNMP requests. Consider to secure access to router or to router’s SNMP, when SNMP and write-access are enabled.

To change settings by SNMP requests, use the command below to allow SNMP write for the selected community,
Write-access option for SNMP is available from v3.14,

/snmp community set <number> write-access=yes

System Identity

It’s possible to change router system identity by SNMP set command,

snmpset -c public -v 1 192.168.0.0 1.3.6.1.2.1.1.5.0  s New_Identity
  • snmpset — SNMP application used for SNMP SET requests to set information on a network entity;
  • public — router’s community name;
  • 192.168.0.0 — IP address of the router;
  • 1.3.6.1.2.1.1.5.0 — SNMP value for router’s identity;

SNMPset command above is equal to the RouterOS command,

/system identity set identity=New_Identity

Reboot

It’s possible to reboot the router with SNMP set commamd, you need to set value for reboot SNMP settings, which is not equal to 0,

snmpset -c public -v 1 192.168.0.0 1.3.6.1.4.1.14988.1.1.7.1.0 s 1
  • 1.3.6.1.4.1.14988.1.1.7.1.0, SNMP value for the router reboot;
  • s 1, snmpset command to set value, value should not be equal to 0;

Reboot snmpset command is equal to the RouterOS command,

/system reboot

Run Script

SNMP write allows to run scripts on the router from system script menu, when you need to set value for SNMP setting of the script,

 
snmpset -c public -v 1 192.168.0.0 1.3.6.1.4.1.14988.1.1.8.1.1.3.X s 1
  • X, script number, numeration starts from 1;
  • s 1, snmpset command to set value, value should not be equal to 0;

The same command on RouterOS,


/system script> print 
Flags: I - invalid 
 0   name="test" owner="admin" policy=ftp,reboot,read,write,policy,
test,winbox,password,sniff last-started=jan/01/1970
01:31:57 run-count=23 source=:beep 

/system script run 0

Runing scripts with GET

It is possible to run /system scripts via SNMP GET request of the script OID (since 6.37). For this to work SNMP community with write permission is required. OIDs for scripts can be retrieved via SNMPWALK command as the table is dynamic.

Add script:

/system script
add name=script1 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\
   "/sy reboot "
add name=script2 owner=admin policy=ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon source=\
   ""

Get the script OID table

$ snmpwalk -v2c -cpublic 192.168.88.1 1.3.6.1.4.1.14988.1.1.8
iso.3.6.1.4.1.14988.1.1.8.1.1.2.1 = STRING: "script1"
iso.3.6.1.4.1.14988.1.1.8.1.1.2.2 = STRING: "script2"
iso.3.6.1.4.1.14988.1.1.8.1.1.3.1 = INTEGER: 0
iso.3.6.1.4.1.14988.1.1.8.1.1.3.2 = INTEGER: 0

To run script use table 18

$ snmpget -v2c -cpublic 192.168.88.1 1.3.6.1.4.1.14988.1.1.18.1.1.2.2
iso.3.6.1.4.1.14988.1.1.18.1.1.2.2 = STRING: "output"

Monitoring DISK temperature

If you are fortunate enough to have a PC which is supported by
the Mother Board Monitor program, you can just use that and add the appropriate
SNMP objects as described above, or you may find that SpeedFan can also report disk temperature. 
My older PCs did not support MBM or SpeedFan for this, so I wrote a
small program which accesses the S.M.A.R.T. data provided by some hard disks and
the BIOS.  Not all PCs do this, and not all PCs make all of the data
accessible.  To test your PC, , and run it from the command-line.  Note that on Windows
Vista and later, the program will have to be run in Administrator mode.  You should
see four lines like:

C:\>DiskTemp.exe
30
33
0
0

C:\>

So as the program returns the disk temperatures (of the
two disks on this PC), you can plot it in MRTG like this, using the ability
of MRTG to read the output of a command-line program.

Contents of narvik-disk-temp.inc

#---------------------------------------------------------------
# PC Narvik - disk temperatures
#---------------------------------------------------------------

Target: `DiskTemp`
MaxBytes: 100
MaxBytes2: 100
Title: Disk temperatures for PC Narvik
Options: integer, gauge, nopercent, growright, unknaszero
YLegend: Temperature °C
ShortLegend: °C
Legend1: Disk 0 temperature in °C
Legend2: Disk 1 temperature in °C
LegendI: Disk 0:
LegendO: Disk 1:
PageTop: <H1>PC Narvik -- Disk Temperatures</H1>

Here’s some current data:

PC Kiruna
Disk temperatures3 TB WD Red — D: E:3 TB WD Red — F:

Here’s another example, showing what happened when I replaced
a 750GB 7200rpm standard disk with a 1TB «eco» disk spinning at just
5400rpm, and with a slower seek speed.  While the green line is more or
less constant allowing for the daily temperature changes, the blue line showing
the second disk on PC Narvik has dropped significantly from being a few degrees
above the 750GB disk to being a degree or three below.  A lower working
temperature should produce greater reliability, and it’s a few watts less power
consumption.  Performance of the PC appears to be unaffected.
The horizontal lines from before 0800 to after 1100 were the nonexistent values
while the PC was powered down for the disk clone.  After seeing those
misleading values, I added unknaszero to the options shown above.

Vista and Windows-7/8

I found that the code I used required to be run in
Administrator mode with Windows Vista and Windows-7 and -8, which meant that I could
not start MRTG automatically at startup.  I decided that the best way to
work round this problem was to write a separate program ()
to read the disk temperatures, and then deposit a file in the \MRTG\bin\
directory so that MRTG could read the data with the configuration:

Air Temperature


For air-termperature monitoring upstairs and downstairs I use a couple of simple USB sensors:

coupled with a simple program I wrote myself.  The MRTG config lines are much like the disk
temperature lines above.  If you are interested in a copy of the Windows program, look here.
 If the product URL has changed, look for the product «USB TEMPer» on the site.
 Update Oct-2012: they now offer «gold TEMPer»,
but I don’t know whether this is compatible with my software.

One thing I have been playing with since June 2011 is to record the
temperatures as 1000 times the actual value, i.e. milli-degrees.  
This has two consequences — first that the data from the probes can be
recorded with greater precision.  Although the probes are only accurate
to within a couple of degrees, they do record the data to greater precison —
perhaps half or a quarter degree C.  Secondly, and perhaps more
importantly, using milli-degrees allows MRTG to record a more precise average
for the week, month and year graphs which are no longer limited to integer
temperature values.  To allow this, the program has an option to multiply
returned values by 1000, enabled with the -1K parameter.
For outside tempertures, which could be negative Celsius, I have decided to
record Fahrenheit which are most unlikely to go negative here in Edinburgh.
 This is enabled with the -F option to the program.
MRTG would normally display values such as 20,000 (i.e. from 20°C) as «20.0 k»,
where the «k» is the standard thousands units multiplier.  With capital
«K» also being temperature in Kelvins, this is doubly undesriable, so the
display of the units multipler is supressed with the «kMG» entry (see below).
 To make the value displayed below the graphs correct, the «Factor» entry
is set to 0.001.  Fortunately, although the documentation doesn’t say so
explicitly, a floating point value is accepted here as the multipler.

Example graphs may be found here.

Ideas for the contents of: narvik-air-temperatures.inc

#---------------------------------------------------------------
#	PC Narvik - Example for indoor air temperature
#---------------------------------------------------------------

Target: `GetAirTemp  -1K`
MaxBytes: 100000
MaxBytes2: 100000
Title: Air temperature for PC Narvik
Options: integer, gauge, nopercent, growright, unknaszero, noo
YLegend: Temperature °C
ShortLegend: °C
kMG: ,,
Factor: 0.001
Legend1: Air temperature in °C
LegendI: Air temperature °C
PageTop: <H1>PC Narvik -- Air Temperature</H1>

#---------------------------------------------------------------
#	PC Narvik - Example for outside air temperature
#---------------------------------------------------------------

Target: `GetAirTemp -1K  -F`
MaxBytes: 140000
MaxBytes2: 140000
Title: Outside air temperature
Options: integer, gauge, nopercent, growright, unknaszero, noo
YLegend: Temperature °F
ShortLegend: °F
kMG: ,,
Factor: 0.001
Legend1: Outside air temperature in °F
LegendI: Outside Air temperature °F
PageTop: <H1>Outside Air Temperature</H1>

The program has since been updated to handle the dual temperature and humidity
probe offered by the same vendor, taking the -T or -H parameter to specify
whether Temperature or Humidity should be returned. The MRTG lines for using
this facility are:

Temperarture & humidity version of: narvik-air-temperatures.inc

#---------------------------------------------------------------
#	PC Narvik - Ambient air temperature
#---------------------------------------------------------------

Target: `GetAirTemp  -1K  -T`
MaxBytes: 100000
MaxBytes2: 100000
Title: Ambient air temperature for PC Narvik
Options: integer, gauge, nopercent, growright, unknaszero, noo
YLegend: Temperature °C
ShortLegend: °C
kMG: ,
Factor: 0.001
Legend1: Ambient air temperature in °C
LegendI: Ambient Air temperature
PageTop: <H1>Upstairs -- Ambient Air Temperature</H1>

#---------------------------------------------------------------
#	PC Narvik - Humidity
#---------------------------------------------------------------

Target: `GetAirTemp  -1K  -H`
MaxBytes: 100000
MaxBytes2: 100000
Title: Relative humidity for PC Narvik
Options: integer, gauge, nopercent, growright, unknaszero, noi
YLegend: Humidity %
ShortLegend: %
kMG: ,
Factor: 0.001
Legend2: Relative humidity %
LegendO: Relative Humidity
PageTop: <H1>Upstairs Air -- Relative Humidity</H1>
      

Causes of Help configuring MRTG on Ubuntu 8.04?

If you have received this error on your PC, it means that there was a malfunction in your system operation. Common reasons include incorrect or failed installation or uninstallation of software that may have left invalid entries in your Windows registry, consequences of a virus or malware attack, improper system shutdown due to a power failure or another factor, someone with little technical knowledge accidentally deleting a necessary system file or registry entry, as well as a number of other causes. The immediate cause of the «Help configuring MRTG on Ubuntu 8.04» error is a failure to correctly run one of its normal operations by a system or application component.

Конец MRTG-2

  • Простая установка: конфигурация хранится в простых текстовых файлах. Дополнительные утилиты позволяют создавать первичную версию конфигурационного файла, ориентированного для конкретного роутера.
  • Легкая поддержка: так как размер и временное разрешение лог-файлов автоматически изменялось во время работы, система могла работать без дополнительного вмешательства месяцами.
  • Дружественность: HTML-страницы, генерируемые MRTG, были просты для восприятия и давали хорошее визуальное представление загрузки сети, предлагая основанные на логах предложения об обновлении сетевых каналов связи.
  • Интегрированное решение: MRTG выполнял все задачи, связанные с мониторингом трафика. Для его работы не требовалось никаких внешних баз данных или пакетов SNMP.

Главными проблемными зонами MRTG-2 были следующие:

Производительность: MRTG-2 не мог мониторить больше чем около 600 портов роутера в 5-минутный интервал по причине того, как он работал с лог-файлами.

Гибкость: хотя MRTG-2 был весьма конфигурируемым, пользователям требовалось проявлять особую осторожность в местах, где способность к конфигурированию была ограниченной. В частности, при использовании программы для мониторинга временно-зависимых данных, а не сетевого трафика.. Тот факт, что люди использовали MRTG для задач, для которых он изначально не предполагался, привел к большой модификации MRTG, что в результате дало уникальную возможность интегрировать наборы данных, хранилище, консолидацию и визуализацию в одном пакете

Поэтому главными целями MRTG-3 стали гибкость и скорость.

Тот факт, что люди использовали MRTG для задач, для которых он изначально не предполагался, привел к большой модификации MRTG, что в результате дало уникальную возможность интегрировать наборы данных, хранилище, консолидацию и визуализацию в одном пакете. Поэтому главными целями MRTG-3 стали гибкость и скорость.

Configuring MRTG

Once the installation process is complete, you need to configure it before you can start monitoring target devices. We’ll set MRTG working directory to be /var/www/mrtg

# mkdir /var/www/mrtg

Make sure to change owner of this directory to , which is the default user account for Apache web server.

# chown -R www-data:www-data /var/www/mrtg

Then edit /etc/mrtg.conf to set Working directory:

# cat /etc/mrtg.cfg | grep -v "^#"

WorkDir: /var/www/mrtg
WriteExpires: Yes
Title: Traffic Analysis for

Rebuild MRTG configuration from modified file:

# cfgmaker public@localhost > /etc/mrtg.cfg
--base: Get Device Info on public@localhost:
--base: Vendor Id: Unknown Vendor - 1.3.6.1.4.1.8072.3.2.10
--base: Populating confcache
--base: Get Interface Info
--base: Walking ifIndex
--snpd: public@localhost: -> 1 -> ifIndex = 1
--snpd: public@localhost: -> 2 -> ifIndex = 2
--snpd: public@localhost: -> 3 -> ifIndex = 3
--base: Walking ifType
--snpd: public@localhost: -> 1 -> ifType = 24
--snpd: public@localhost: -> 2 -> ifType = 6
--snpd: public@localhost: -> 3 -> ifType = 6
--base: Walking ifAdminStatus
--snpd: public@localhost: -> 1 -> ifAdminStatus = 1
--snpd: public@localhost: -> 2 -> ifAdminStatus = 1
--snpd: public@localhost: -> 3 -> ifAdminStatus = 1
--base: Walking ifOperStatus
--snpd: public@localhost: -> 1 -> ifOperStatus = 1
--snpd: public@localhost: -> 2 -> ifOperStatus = 1
--snpd: public@localhost: -> 3 -> ifOperStatus = 1
--base: Walking ifMtu
--snpd: public@localhost: -> 1 -> ifMtu = 65536
--snpd: public@localhost: -> 2 -> ifMtu = 1500
--snpd: public@localhost: -> 3 -> ifMtu = 1500
--base: Walking ifSpeed
--snpd: public@localhost: -> 1 -> ifSpeed = 10000000
--snpd: public@localhost: -> 2 -> ifSpeed = 0
--snpd: public@localhost: -> 3 -> ifSpeed = 0
# ls /var/www/mrtg/
index.html mrtg-l.png mrtg-m.png mrtg-r.png

Create index file for web server:

# indexmaker /etc/mrtg.cfg > /var/www/mrtg/index.html

The last thing to do is create a VirtualHost file for the site.

# vim /etc/apache2/sites-available/mrtg.conf

Add the following to this new file:

Alias /mrtg "/var/www/mrtg/"
​<Directory "/var/www/mrtg/">
 ​Options None
​ AllowOverride None
​ Require all granted
​</Directory>

Enable the site and reload apache service.

# sudo a2ensite mrtg

Reload Apache service:

# systemctl reload apache2

Meaning of Anyone installed MRTG on Windows 2003??

Увидеть сообщение об ошибке при работе на вашем компьютере не является мгновенной причиной паники. Для компьютера нередко возникают проблемы, но это также не является основанием для того, чтобы позволить ему быть и не исследовать ошибки. Ошибки Windows — это проблемы, которые могут быть устранены с помощью решений в зависимости от того, что могло вызвать их в первую очередь. Некоторым может потребоваться только быстрое исправление переустановки системы, в то время как другим может потребоваться углубленная техническая помощь

Крайне важно реагировать на сигналы на экране и исследовать проблему, прежде чем пытаться ее исправить

Дополнительные материалы

Фрагмент конфигурации для наблюдения за гигабитными интерфейсами

# Target: 3:public@router:::::2   # For Gigabit Interfaces
### Interface 1 >> Descr: 'FastEthernet0/1' | Name: 'Fa0/1' | Ip: '' | Eth: '00-0d-29-e7-7e-01' ###

Фрагмент конфигурации для наблюдения за загрузкой процессора

Target: 1.3.6.1.4.1.9.2.1.56.0&1.3.6.1.4.1.9.2.1.57.0:public@switch:
MaxBytes: 100
Title: switch (switch): CPU
Options: gauge, nopercent
PageTop: <H1>Analysis for switch CPU load
 </H1>
 <TABLE>
   <TR><TD>System:</TD><TD>switch in AIS lab., BMSTU</TD></TR>
   <TR><TD>Maintainer:</TD><TD>root@gate.corpX.un</TD></TR>
   <TR><TD>Interface:</TD><TD>CPU</TD></TR>
   <TR><TD>IP:</TD><TD>switch (switch)</TD></TR>
   <TR><TD>Max load:</TD>
       <TD>100%</TD></TR>
  </TABLE>

Использование скриптов

# cat /etc/mrtg-dhcp-stat.sh
#!/bin/sh

#CMD='rsh router show ip dhcp binding | grep 192.168 | wc -l'
#MAX=99
#CUR=`eval $CMD`

#CMD='/usr/bin/dhcpd-pools -l /var/lib/dhcp/dhcpd.leases -c /etc/dhcp/dhcpd.conf -f c | grep 192.168.X.'
#CMD='/usr/local/bin/dhcpd-pools -l /var/db/dhcpd/dhcpd.leases -c /usr/local/etc/dhcpd.conf -f c | grep 192.168.X.'
#MAX=`eval $CMD | cut -d'"' -f8`
#CUR=`eval $CMD | cut -d'"' -f10`

echo $MAX
echo $CUR
echo 0
echo 0
# cat mrtg.cfg
...
Target: `/etc/mrtg-dhcp-stat.sh`
Title: dhcp stat (ip)
PageTop: <H1>dhcp stat (ip)</H1>
Options: nobanner,gauge,noinfo,nopercent
MaxBytes: 100
Unscaled: dwmy
YLegend: Hosts (ip)
ShortLegend: ip
LegendI: dhcp leased
LegendO: max ip in pool
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *