Страницы

Raspberry Pi - Система мониторинга Nagios

Что такое Nagios? Это свободная система с открытым исходным кодом, предназначенная для мониторинга компьютерных сетей и серверов. Система используется для контроля состояния сетевых служб и устройств, а также для оповещения администраторов сети о возникающих неисправностях или отказах.




С помощью Nagios и Raspberry Pi можно создать недорогой сервер для выполнения таких задач, как работа по мониторингу, сканирование сети, а также наблюдение за сетевой активностью.

В этой статье я хочу рассказать об установке Nagios на Raspberry Pi.

В качестве операционной системы я использовал SD карту с образом Debian «squeeze» (прим. переводчика: в настоящее время актуальная версия ОС — Raspbian «wheezy», который построен на основе Debian «wheeze». Скачать версию, указанную в статье можно здесь, актуальные версии доступны здесь). Инструкции по установке образа системы можно найти ниже в блоге. Для установки понадобится SD карта, объемом не менее 2 Гб (желательно больше).

Как только SD карта будет готова — вставляйте её в Raspberry Pi и включайте его! Хорошим ходом будет запустить ssh демон, чтобы иметь возможность работать удалённо, но это на ваш выбор.

Нам придется устанавливать много пакетов с помощью apt-get, поэтому будет лучше обновить его базу данных (если вы находитесь за прокси-сервером, используйте «export http_proxy=http://xxx.xxx.xxx.xxx:yyyyyy» для указания адреса прокси программе apt-get).

Обратите внимание, что Debian имеет заранее скомпилированный пакет Nagios (3.2), который можно очень просто установить командой: apt-get install nagios3.

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

Во-первых — обновите базу доступных пакетов программ:root@raspberrypi:/home/pi# sudo apt-get update

Перед компиляцией Nagios требуется установить необходимые пакеты:root@raspberrypi:/home/pi# sudo apt-get install php5 apache2 libgd2-xpm libgd2-xpm-dev libgd2-dev libpng12-dev libjpeg62-dev libgd-tools libpng12-dev libgd2-xpm libgd2-xpm-dev libssl-dev gnutls-bin iputils

Также требуется создать группы пользователей для Nagios и apache:root@raspberrypi:/home/pi# groupadd www-data root@raspberrypi:/home/pi# groupadd nagios

Теперь создадим пользователя Nagios:root@raspberrypi:/home/pi# adduser nagios Adding user `nagios’ … Adding new group `nagios’ (1001) … Adding new user `nagios’ (1002) with group `nagios’ … Creating home directory `/home/nagios’ … Copying files from `/etc/skel’ … Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully Changing the user information for nagios Enter the new value, or press ENTER for the default Full Name []: Nagios Room Number []: Nagios Work Phone []: Home Phone []: Other []: Is the information correct? [Y/n] Y root@raspberrypi:/home/pi# grep nagios /etc/passwd nagios:x:1002:1001:Nagios,Nagios,,:/home/nagios:/bin/bash

Теперь добавим пользователей в соответствующие группы:root@raspberrypi:/home/pi# usermod -G nagios nagios root@raspberrypi:/home/pi# usermod -G www-data,nagios www-data

Проверяем сделанные изменения:root@raspberrypi:/home/pi# grep nagios /etc/group <nagios:x:1001:www-data,Nagios

Готовим установочный каталог:root@raspberrypi:/home/pi# mkdir /usr/local/nagios root@raspberrypi:/home/pi# chown -R nagios:nagios /usr/local/Nagios

Также потребуется установить GD-Utils:root@raspberrypi:/tmp# wget http://www.boutell.com/gd/http /gd-2.0.33.tar.gz root@raspberrypi:/tmp# tar -zxvf gd-2.0.33.tar.gz root@raspberrypi:/tmp/gd-2.0.33# ./configure root@raspberrypi:/tmp/gd-2.0.33# make && make install

Установка Nagios

Теперь всё готово. Приступаем к компиляции и установке Nagios:root@raspberrypi:/tmp# wget http://prdownloads.sourceforge.net /sourceforge/nagios/nagios-3.4.1.tar.gz root@raspberrypi:/tmp# tar xzf nagios-3.4.1.tar.gz root@raspberrypi:/tmp/nagios# ./configure –prefix=/usr/local /nagios –with-cgiurl=/nagios/cgi-bin –with-htmurl=/nagios/ –with-nagios-user=nagios –with-nagios-group=nagios –with-command-group=nagios ................... *** Configuration summary for nagios 3.4.1 05-11-2012 ***: General Options: ---------------- Nagios executable: nagios Nagios user/group: nagios,nagios Command user/group: nagios,nagios Embedded Perl: no Event Broker: yes Install ${prefix}: /usr/local/nagios Lock file: ${prefix}/var/nagios.lock Check result directory: ${prefix}/var/spool/checkresults Init directory: /etc/init.d Apache conf.d directory: /etc/apache2/conf.d Mail program: /bin/mail Host OS: linux-gnu Web Interface Options: ---------------------- HTML URL: http://localhost/nagios/ CGI URL: http://localhost/nagios/cgi-bin/ Traceroute (used by WAP): /usr/sbin/traceroute Review the options above for accuracy. If they look okay, type ‘make all’ to compile the main program and CGIs.

Теперь запускаем команду make:root@raspberrypi:/tmp/nagios# make all make[1]: Leaving directory `/tmp/nagios/module’ *** Compile finished *** If the main program and CGIs compiled without any errors, you can continue with installing Nagios as follows (type ‘make’ without any arguments for a list of all possible options): make install - This installs the main program, CGIs, and HTML files make install-init - This installs the init script in /etc/init.d make install-commandmode - This installs and configures permissions on the directory for holding the external command file make install-config - This installs *SAMPLE* config files in /usr/local/nagios/etc You’ll have to modify these sample files before you can use Nagios. Read the HTML documentation for more info on doing this. Pay particular attention to the docs on object configuration files, as they determine what/how things get monitored! make install-webconf - This installs the Apache config file for the Nagios web interface make install-exfoliation - This installs the Exfoliation theme for the Nagios web interface make install-classicui - This installs the classic theme for the Nagios web interface *** Support Notes ******************************************* If you have questions about configuring or running Nagios, please make sure that you: - Look at the sample config files - Read the documentation on the Nagios Library at: http://library.nagios.com before you post a question to one of the mailing lists. Also make sure to include pertinent information that could help others help you. This might include: - What version of Nagios you are using - What version of the plugins you are using - Relevant snippets from your config files - Relevant error messages from the Nagios log file For more information on obtaining support for Nagios, visit: http://support.nagios.com ************************************************************* Enjoy.

Наконец запускаем:root@raspberrypi:/tmp/nagios# make install

По умолчанию Nagios устанавливается с темой Exfoliation.

Кроме этого, нам понадобится создать скрипт инициализации:root@raspberrypi:/tmp/nagios# make install-init

Создаем и настраиваем каталог для хранения внешних командных файлов:root@raspberrypi:/tmp/nagios# make install-commandmode

Создаем файл конфигурации сервера apache:root@raspberrypi:/tmp/nagios# make install-webconf

И наконец, создаем образцы конфигурационных файлов:root@raspberrypi:/tmp/nagios# make install-config

Теперь перезапустим демона apache:root@raspberrypi:/tmp/nagios# /etc/init.d/apache2 reload

Установка плагинов Nagios

Мы можем установить плагины двумя способами:

С помощью менеджера пакетов (не забудьте исправить в плагинах переменную $USER1$ так, чтобы она указывала на каталог с установленным Nagios):sudo apt-get install nagios-plugins nagios-snmp-plugins

Либо можно скомпилировать плагины самостоятельно:root@raspberrypi:/tmp# wget http://prdownloads.sourceforge.net /sourceforge/nagiosplug/nagios-plugins-1.4.15.tar.gz root@raspberrypi:/tmp# tar xzf nagios-plugins-1.4.15.tar.gz root@raspberrypi:/tmp/nagios-plugins-1.4.15# ./configure root@raspberrypi:/tmp/nagios-plugins-1.4.15# make && make install

На этом всё! Осталось проверить файл конфигурации:root@raspberrypi:/tmp# /usr/local/nagios/bin/nagios -v /usr/local /nagios/etc/nagios.cfg


И, наконец, запускаем демона!root@raspberrypi:/tmp# service nagios start


Вуаля! Nagios установлен на Raspberry Pi!!!

(Примечание автора: если вы обратите внимание, то на предыдущем снимке экрана видно, что система находится под чрезвычайно высокой нагрузкой! Не придавайте этому большого значения, т.к. снимок сделан во время стресс-теста системы)

На этом всё!