1.Установка и настройка Nagios-сервера
Создание пользователя nagios и группы nagcmd
1 |
# useradd nagios |
1 |
# groupadd nagcmd |
Добавление пользователей nagios и www-data в группу nagcmd для того,чтобы выполнять внешние команды на Nagios-сервере через WEB-интерфейс
1 |
# usermod -a -G nagcmd nagios && usermod -a -G nagcmd www-data |
1 |
# grep nagios /etc/group |
1 2 |
nagios:x:1001: nagcmd:x:1002:nagios,www-data |
Установка Apahce и PHP
Установка необходимых пакетов/зависимостей для Nagios
1 |
# apt-get install apache2 php5-gd libapache2-mod-php5 |
1 |
# apt-get install build-essential unzip openssl libssl-dev libgd2-xpm-dev apache2-utils |
Последняя стабильная версия недоступна через репозитарии Debian.
Поэтому установку будем производить их исходного кода
Загружаем и извлекаем архив Nagios-сервера
1 |
# cd /tmp && wget https://assets.nagios.com/downloads/nagioscore/releases/nagios-4.2.0.tar.gz |
1 |
# tar -xvf nagios-4.*.tar.gz |
1 |
# rm /tmp/nagios-4.2.4.tar.gz |
Переходим в вновь созданный каталог
1 |
# cd nagios-4.* |
Конфигурируем,компилируем и устанавливаем Nagios
1 |
# ./configure --with-nagios-group=nagios --with-command-group=nagcmd |
1 |
# make all |
1 |
# make install |
1 |
# make install-init |
1 |
# make install-config |
1 |
# make install-commandmode |
Включаем/активируем модули Apache rewrite и cgi
1 |
# a2enmod rewrite && a2enmod cgi |
Копируем вирт.хост Nagios в каталог sites-available
1 |
# cp sample-config/httpd.conf /etc/apache2/sites-available/nagios4.conf |
Устаналиваем права доступа на файл вирт.хоста
1 |
# chmod 644 /etc/apache2/sites-available/nagios4.conf |
Включаем вирт.хост Nagios
1 |
# a2ensite nagios4.conf |
Создаем пользователя для доступа в WEB-интерфейс Nagios
1 |
# htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin |
Также создам отдельного пользователя (в дальнейшем этот пользователь в конф.файле cgi.cfg будет наделен такими же правами,как и пользователя nagiosadmin)
1 |
# htpasswd /usr/local/nagios/etc/htpasswd.users myuser |
Перезапускаем Apache
1 |
# service apache2 restart |
1 |
# cp -R contrib/eventhandlers/ /usr/local/nagios/libexec/ |
2.Установка Nagios-плагинов на Nagios-сервере
1 |
# cd /tmp |
1 |
# wget http://nagios-plugins.org/download/nagios-plugins-2.1.4.tar.gz |
1 |
# tar -zxf nagios-plugins-* |
1 |
# rm /tmp/nagios-plugins-2.1.4.tar.gz |
1 |
# cd nagios-plugins-* |
Конфигурируем,компилируем и устанавливаем Nagios-plugins
1 |
# ./configure --with-nagios-user=nagios --with-nagios-group=nagios --with-openssl |
1 |
# make |
1 |
# make install |
Можно также устанавливать плагины из пакетов стандартного репозитария вместо установки из исходного кода
1 |
# apt-get install nagios-plugins nagios-plugins-basic nagios-plugins-extra |
Проверка синтаксиса конфигурационных файлов Nagios
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg |
Для Debian8/Ubuntu 16
Создаем скрипт для управления Nagios через систему инициализации systemd
1 |
# nano /etc/systemd/system/nagios.service |
1 2 3 4 5 6 7 8 9 10 11 12 |
[Unit] Description=Nagios BindTo=network.target [Install] WantedBy=multi-user.target [Service] User=nagios Group=nagios Type=simple ExecStart=/usr/local/nagios/bin/nagios /usr/local/nagios/etc/nagios.cfg |
Добавляем Nagios в автозагрузку, запукаем и проверяем корректность запуска
Для Debian8/Ubuntu 16
1 |
# systemctl enable /etc/systemd/system/nagios.service |
1 |
Created symlink from /etc/systemd/system/multi-user.target.wants/nagios.service to /etc/systemd/system/nagios.service. |
1 |
# systemctl start nagios |
1 |
# systemctl status nagios |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
● nagios.service - Nagios Loaded: loaded (/etc/systemd/system/nagios.service; enabled) Active: active (running) since Sat 2016-08-27 16:31:50 EEST; 14s ago Main PID: 36911 (nagios) CGroup: /system.slice/nagios.service ├─36911 /usr/local/nagios/bin/nagios /usr/local/nagios/etc/nagios.cfg ├─36912 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh ├─36913 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh ├─36914 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh ├─36915 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh ├─36916 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh ├─36917 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh └─36918 /usr/local/nagios/bin/nagios /usr/local/nagios/etc/nagios.cfg |
Для Ubuntu 14
1 |
# update-rc.d nagios defaults |
1 |
# /etc/init.d/nagios start |
1 |
# /etc/init.d/nagios status |
1 |
nagios (pid 4694) is running... |
1 |
# ps ax | grep [n]agios |
1 2 3 4 5 6 7 8 |
4694 ? Ss 0:00 /usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg 4695 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4696 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4697 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4698 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4699 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4700 ? S 0:00 /usr/local/nagios/bin/nagios --worker /usr/local/nagios/var/rw/nagios.qh 4701 ? S 0:00 /usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg |
3.Заходим в WEB-интерфейс по URL
1 |
http://IP-address-server/nagios |
c логином nagiosadmin/myuser и паролем, заданным при создании этого пользователя командой htpasswd
4.Настройка конфигурационных файлов Nagios
Изменим структуру катлогов для хранения различных файлов
1 |
# nano /usr/local/nagios/etc/nagios.cfg |
1 2 3 4 5 |
cfg_dir=/usr/local/nagios/etc/commands.d cfg_dir=/usr/local/nagios/etc/contacts.d cfg_dir=/usr/local/nagios/etc/hosts.d cfg_dir=/usr/local/nagios/etc/services.d cfg_dir=/usr/local/nagios/etc/misc.d |
Создадим структуру катлогов и установим корректного владельца/группу
1 |
# mkdir -p /usr/local/nagios/etc/{commands.d,contacts.d,hosts.d,services.d,misc.d} |
1 |
# chown -R nagios:nagios /usr/local/nagios/etc/{commands.d,contacts.d,hosts.d,misc.d,services.d} |
Конфигурационный файл cgi.cfg приводим к виду
1 |
# grep -vE '^$|^#' /usr/local/nagios/etc/cgi.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
main_config_file=/usr/local/nagios/etc/nagios.cfg physical_html_path=/usr/local/nagios/share url_html_path=/nagios show_context_help=1 use_pending_states=1 use_authentication=1 use_ssl_authentication=0 authorized_for_system_information=nagiosadmin,myuser authorized_for_configuration_information=nagiosadmin,myuser authorized_for_system_commands=nagiosadmin,myuser authorized_for_all_services=nagiosadmin,myuser authorized_for_all_hosts=nagiosadmin,myuser authorized_for_all_service_commands=nagiosadmin,myuser authorized_for_all_host_commands=nagiosadmin,myuser default_statusmap_layout=5 default_statuswrl_layout=4 ping_syntax=/bin/ping -n -U -c 5 $HOSTADDRESS$ refresh_rate=60 result_limit=0 escape_html_tags=1 action_url_target=_blank notes_url_target=_blank lock_author_names=1 navbar_search_for_addresses=1 navbar_search_for_aliases=1 |
Конфигурационный файл nagios.cfg приводим к виду
1 |
# grep -vE '^$|^#' /usr/local/nagios/etc/nagios.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
log_file=/usr/local/nagios/var/nagios.log cfg_dir=/usr/local/nagios/etc/commands.d cfg_dir=/usr/local/nagios/etc/contacts.d cfg_dir=/usr/local/nagios/etc/hosts.d cfg_dir=/usr/local/nagios/etc/services.d cfg_dir=/usr/local/nagios/etc/misc.d object_cache_file=/usr/local/nagios/var/objects.cache precached_object_file=/usr/local/nagios/var/objects.precache resource_file=/usr/local/nagios/etc/resource.cfg status_file=/usr/local/nagios/var/status.dat status_update_interval=10 nagios_user=nagios nagios_group=nagios check_external_commands=1 command_file=/usr/local/nagios/var/rw/nagios.cmd lock_file=/usr/local/nagios/var/nagios.lock temp_file=/usr/local/nagios/var/nagios.tmp temp_path=/tmp event_broker_options=-1 log_rotation_method=d log_archive_path=/usr/local/nagios/var/archives use_syslog=1 log_notifications=1 log_service_retries=1 log_host_retries=1 log_event_handlers=1 log_initial_states=1 log_current_states=1 log_external_commands=1 log_passive_checks=1 service_inter_check_delay_method=s max_service_check_spread=30 service_interleave_factor=s host_inter_check_delay_method=s max_host_check_spread=30 max_concurrent_checks=0 check_result_reaper_frequency=2 max_check_result_reaper_time=5 check_result_path=/usr/local/nagios/var/spool/checkresults max_check_result_file_age=3600 cached_host_check_horizon=15 cached_service_check_horizon=15 enable_predictive_host_dependency_checks=1 enable_predictive_service_dependency_checks=1 soft_state_dependencies=1 auto_reschedule_checks=0 auto_rescheduling_interval=30 auto_rescheduling_window=180 service_check_timeout=60 host_check_timeout=30 event_handler_timeout=30 notification_timeout=30 ocsp_timeout=5 perfdata_timeout=5 retain_state_information=1 state_retention_file=/usr/local/nagios/var/retention.dat retention_update_interval=60 use_retained_program_state=1 use_retained_scheduling_info=1 retained_host_attribute_mask=0 retained_service_attribute_mask=0 retained_process_host_attribute_mask=0 retained_process_service_attribute_mask=0 retained_contact_host_attribute_mask=0 retained_contact_service_attribute_mask=0 interval_length=60 check_for_updates=0 bare_update_check=1 use_aggressive_host_checking=0 execute_service_checks=1 accept_passive_service_checks=1 execute_host_checks=1 accept_passive_host_checks=1 enable_notifications=1 enable_event_handlers=1 process_performance_data=0 obsess_over_services=0 obsess_over_hosts=0 translate_passive_host_checks=0 passive_host_checks_are_soft=0 check_for_orphaned_services=1 check_for_orphaned_hosts=1 check_service_freshness=1 service_freshness_check_interval=60 service_check_timeout_state=c check_host_freshness=0 host_freshness_check_interval=60 additional_freshness_latency=15 enable_flap_detection=0 low_service_flap_threshold=5.0 high_service_flap_threshold=20.0 low_host_flap_threshold=5.0 high_host_flap_threshold=20.0 date_format=iso8601 illegal_object_name_chars=`~!$%^&*|'"<>?,()= illegal_macro_output_chars=`~$&|'"<> use_regexp_matching=0 use_true_regexp_matching=0 admin_email=myuser@mydomain.com admin_pager=myuser@mydomain.com daemon_dumps_core=0 use_large_installation_tweaks=1 enable_environment_macros=1 debug_level=0 debug_verbosity=0 debug_file=/usr/local/nagios/var/nagios.debug max_debug_file_size=1000000 allow_empty_hostgroup_assignment=0 host_down_disable_service_checks=1 |
Файл с описанием временных периодов
1 |
# nano /usr/local/nagios/etc/misc.d/timeperiods.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
define timeperiod{ timeperiod_name 24x7 alias 24 Hours A Day, 7 Days A Week sunday 00:00-24:00 monday 00:00-24:00 tuesday 00:00-24:00 wednesday 00:00-24:00 thursday 00:00-24:00 friday 00:00-24:00 saturday 00:00-24:00 } # 'workhours' timeperiod definition define timeperiod{ timeperiod_name workhours alias Normal Work Hours monday 09:00-18:00 tuesday 09:00-18:00 wednesday 09:00-18:00 thursday 09:00-18:00 friday 09:00-18:00 } # not 'workhours' timeperiod definition define timeperiod{ timeperiod_name non-workhours alias Normal Work Off Hours monday 00:00-09:00,18:00-24:00 tuesday 00:00-09:00,18:00-24:00 wednesday 00:00-09:00,18:00-24:00 thursday 00:00-09:00,18:00-24:00 friday 00:00-09:00,18:00-24:00 saturday 00:00-24:00 sunday 00:00-24:00 } # 'none' timeperiod definition define timeperiod{ timeperiod_name none alias Never } |
Настройка контактов/групп контактов оповещения
Создаем общий шаблон контактов
1 |
# /usr/local/nagios/etc/contacts.d/contacts-template.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define contact { name contact-template-generic host_notifications_enabled 1 service_notifications_enabled 1 host_notification_period 24x7 service_notification_period 24x7 host_notification_options d,u,r service_notification_options w,u,c,r can_submit_commands 1 retain_status_information 1 retain_nonstatus_information 1 register 0 } |
Создаем шаблон контаков для оповещения по E-Mail
1 |
# nano /usr/local/nagios/etc/contacts.d/contacts-email.cfg |
1 2 3 4 5 6 7 |
define contact { name contact-template-email use contact-template-generic host_notification_commands notify-host-by-email service_notification_commands notify-service-by-email register 0 } |
Создаем группу контактов
1 |
# nano /usr/local/nagios/etc/contacts.d/contactgroups-administrator.cfg |
1 2 3 4 5 |
define contactgroup { contactgroup_name admins alias All Administrators members evgen.k } |
Создаем контакт
1 |
# nano /usr/local/nagios/etc/contacts.d/contacts.cfg |
1 2 3 4 5 6 7 |
define contact { contact_name evgen.k alias MyName MyUserName email myname@mydomain.com use contact-template-email } |
Настройка шаблонов описания хоста
Создаем общий шаблон хоста
1 |
# nano /usr/local/nagios/etc/hosts.d/host-template-generic.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
define host { name host-template-generic check_command check-host-alive initial_state u max_check_attempts 3 check_interval 1 retry_interval 1 active_checks_enabled 1 passive_checks_enabled 1 check_period 24x7 obsess_over_host 1 check_freshness 1 event_handler_enabled 1 flap_detection_enabled 0 process_perf_data 0 retain_status_information 1 retain_nonstatus_information 1 notification_interval 20 first_notification_delay 3 notification_period 24x7 notification_options d,u,r,s notifications_enabled 1 register 0 } |
Создаем шаблон с оповещением группы admins по определенным состояниям хоста
1 |
# nano /usr/local/nagios/etc/hosts.d/host-template.cfg |
1 2 3 4 5 6 7 |
define host { name host-template use host-template-generic contact_groups admins notification_options d,r,s register 0 } |
Создаем хост-группу, в которой будет всего один хост — localhost
1 |
# nano /usr/local/nagios/etc/hosts.d/hostgroup.cfg |
1 2 3 4 5 |
define hostgroup { hostgroup_name localhost alias Local servers members localhost } |
Создаем файл описания хоста localhost
1 |
# nano /usr/local/nagios/etc/hosts.d/hosts.cfg |
1 2 3 4 5 6 7 8 |
define host { host_name localhost alias localhost display_name localhost address 127.0.0.1 use host-template } |
Настройка шаблонов описания служб/сервисов
Создаем общий шаблон сервиса
1 |
# nano /usr/local/nagios/etc/services.d/service-template-generic.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
define service { name service-template-generic is_volatile 0 initial_state u max_check_attempts 3 check_interval 1 retry_interval 1 active_checks_enabled 1 passive_checks_enabled 1 check_period 24x7 check_freshness 1 event_handler_enabled 1 flap_detection_enabled 0 process_perf_data 0 retain_status_information 1 retain_nonstatus_information 1 notification_interval 20 first_notification_delay 3 notification_period 24x7 notification_options w,u,c,r,f,s notifications_enabled 1 register 0 } |
Создаем шаблон с оповещением группы admins по определенным состояниям служб
1 |
# nano /usr/local/nagios/etc/services.d/service-template.cfg |
1 2 3 4 5 6 7 |
define service { name service-template use service-template-generic notification_options w,u,c,r,s contact_groups admins register 0 } |
Создаем файл описания служб для хоста localhost(он единственный входит в группу localhost)
1 |
# nano /usr/local/nagios/etc/services.d/services.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
define service{ hostgroup_name localhost use service-template service_description PING check_command check_ping!100.0,20%!500.0,60% max_check_attempts 10 } define service{ hostgroup_name localhost use service-template service_description Root Partition check_command check_local_disk!20%!10%!/ } define service{ hostgroup_name localhost use service-template service_description Current Users check_command check_local_users!20!50 } define service{ hostgroup_name localhost use service-template service_description Total Processes check_command check_local_procs!250!400!RSZDT } define service{ hostgroup_name localhost use service-template service_description Current Load check_command check_local_load!5.0,4.0,3.0!10.0,6.0,4.0 } define service{ hostgroup_name localhost use service-template service_description Swap Usage check_command check_local_swap!20!10 } define service{ hostgroup_name localhost use service-template service_description SSH check_command check_ssh } define service{ hostgroup_name localhost use service-template service_description HTTP check_command check_http } |
Файл с описанием команд приводим к виду
1 |
# grep -vE '^$|^#' /usr/local/nagios/etc/commands.d/commands.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
define command{ command_name notify-host-by-email command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\nHost: $HOSTNAME$\nState: $HOSTSTATE$\nAddress: $HOSTADDRESS$\nInfo: $HOSTOUTPUT$\n\nDate/Time: $LONGDATETIME$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Host Alert: $HOSTNAME$ is $HOSTSTATE$ **" $CONTACTEMAIL$ } define command{ command_name notify-service-by-email command_line /usr/bin/printf "%b" "***** Nagios *****\n\nNotification Type: $NOTIFICATIONTYPE$\n\nService: $SERVICEDESC$\nHost: $HOSTALIAS$\nAddress: $HOSTADDRESS$\nState: $SERVICESTATE$\n\nDate/Time: $LONGDATETIME$\n\nAdditional Info:\n\n$SERVICEOUTPUT$\n" | /usr/bin/mail -s "** $NOTIFICATIONTYPE$ Service Alert: $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$ **" $CONTACTEMAIL$ } define command{ command_name check-host-alive command_line $USER1$/check_ping -H $HOSTADDRESS$ -w 3000.0,80% -c 5000.0,100% -p 5 } define command{ command_name check_local_disk command_line $USER1$/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$ } define command{ command_name check_local_load command_line $USER1$/check_load -w $ARG1$ -c $ARG2$ } define command{ command_name check_local_procs command_line $USER1$/check_procs -w $ARG1$ -c $ARG2$ -s $ARG3$ } define command{ command_name check_local_users command_line $USER1$/check_users -w $ARG1$ -c $ARG2$ } define command{ command_name check_local_swap command_line $USER1$/check_swap -w $ARG1$ -c $ARG2$ } define command{ command_name check_http command_line $USER1$/check_http -I $HOSTADDRESS$ $ARG1$ } define command{ command_name check_ssh command_line $USER1$/check_ssh $ARG1$ $HOSTADDRESS$ } define command{ command_name check_ping command_line $USER1$/check_ping -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ -p 5 } |
Проверяем синтаксис Nagios и перезапускаем Nagios
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg |
Debian8/Ubuntu 16
1 |
# systemctl restart nagios |
Ubuntu 14
1 |
# /etc/init.d/nagios restart |
5.Добавление нового сервера на мониторинг(например, пару удаленных клиентов)
hosting2.mydomain.com — Ubuntu16-192.168.1.102
chat.mydomain.com – Centos7-192.168.1.103
Добавим описание хостов
1 |
# nano /usr/local/nagios/etc/hosts.d/hosts.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
define host { host_name hosting2.mydomain.com alias hosting2.mydomain.com display_name hosting2.mydomain.com address 192.168.1.102 use host-template } define host { host_name chat.mydomain.com alias chat.mydomain.com display_name chat.mydomain.com address 192.168.1.103 use host-template } |
1 |
# nano /usr/local/nagios/etc/services.d/services.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
define service{ hostgroup_name myproject-remote-servers use service-template service_description PING check_command check_ping!100.0,20%!500.0,60% max_check_attempts 10 } define service{ hostgroup_name myproject-remote-servers use service-template service_description SSH check_command check_ssh } |
Создадим новую host-группу И добавим в нее клиентов
1 |
# nano /usr/local/nagios/etc/hosts.d/hostgroup.cfg |
1 2 3 4 5 |
define hostgroup { hostgroup_name myproject-remote-servers alias myproject-remote-servers members hosting2.mydomain.com, chat.mydomain.com } |
Проверяем синтаксис Nagios и перезапускаем Nagios
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg |
Debian8/Ubuntu 16
1 |
# systemctl restart nagios |
Ubuntu 14
1 |
# /etc/init.d/nagios restart |
В WEB-интерфейсе проверяем наличие добавленного хоста и служб этого хоста
Установка на клиентах NRPE-демона и Nagios-плагинов для мониторинга параметров через NRPE
Клиент на Centos
1 |
# yum install nagios-nrpe nagios-plugins-nrpe nagios-plugins-all |
Клиент на Debian/Ubuntu
1 |
# apt-get install nagios-plugins nagios-plugins-basic nagios-plugins-extra |
Для Debian/Ubuntu NRPE-сервер с пакетов ставить нельзя
Проблема в том, что при установке с пакетов верcия 2.15 не скомпилирована с опцией —enable-command-args, которая позволяет передавать аргументы (сделано это с целью безопасности https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=756479)
Поэтому даже при включенной опции
dont_blame_nrpe=1
передача аргументов от Nagios-сервера к Nagios-клиенту не работает.
Например
1 |
# /usr/local/nagios/libexec/check_nrpe -t 30 -H 192.168.1.102 -c check_swap -a 20 10 |
1 |
CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages. |
В логах NRPE-сервера на клиенте
1 2 |
Jan 08 19:39:36 hosting2 nrpe[31131]: Error: Request contained command arguments! Jan 08 19:39:36 hosting2 nrpe[31131]: Client request was invalid, bailing out... |
Решение — собрать nrpe с исходного кода с поддержкой опции —enable-command-args
1 |
# apt-get install gcc libssl-dev make xinetd |
1 |
# cd /tmp |
1 |
# wget http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz |
1 |
# tar xvf nrpe-*.tar.gz |
1 |
# cd nrpe-* |
1 |
# ./configure --enable-command-args --with-nagios-user=nagios --with-nagios-group=nagios --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu |
1 |
# make all |
1 |
# make install |
1 |
# make install-xinetd |
1 |
# make install-daemon-config |
1 |
# nano /etc/xinetd.d/nrpe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
service nrpe { flags = REUSE socket_type = stream port = 5666 wait = no user = nagios group = nagios server = /usr/local/nagios/bin/nrpe server_args = -c /usr/local/nagios/etc/nrpe.cfg --inetd log_on_failure += USERID disable = no only_from = 127.0.0.1 192.168.1.101 } |
1 |
# systemctl restart xinetd |
1 |
# systemctl enable xinetd |
Настройка конфигурационного файла NRPE-демона на клиентах
Centos
1 |
# cp /etc/nagios/nrpe.cfg /etc/nagios/nrpe.cfg~ |
1 |
# nano /etc/nagios/nrpe.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
log_facility=daemon pid_file=/var/run/nrpe/nrpe.pid server_port=5666 #server_address=127.0.0.1 nrpe_user=nagios nrpe_group=nagios allowed_hosts=127.0.0.1, 192.168.1.101 # Allow connection from Nagios-server dont_blame_nrpe=1 # Allow pass arguments of the commands allow_bash_command_substitution=0 debug=0 command_timeout=10 connection_timeout=30 command[check_users]=/usr/lib64/nagios/plugins/check_users -w $ARG1$ -c $ARG2$ command[check_procs]=/usr/lib64/nagios/plugins/check_procs -w $ARG1$ -c $ARG2$ -s <span class="crayon-sy">$</span><span class="crayon-v">ARG3</span><span class="crayon-sy">$</span> command[check_load]=/usr/lib64/nagios/plugins/check_load -w $ARG1$ -c $ARG2$ command[check_swap]=/usr/lib64/nagios/plugins/check_swap -w $ARG1$ -c $ARG2$ command[check_disk]=/usr/lib64/nagios/plugins/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$ include_dir=/etc/nrpe.d/ |
1 |
# systemctl start nrpe |
1 |
# systemctl enable nrpe |
1 |
# systemctl status nrpe |
Debian/Ubuntu
1 |
# cp /usr/local/nagios/etc/nrpe.cfg /usr/local/nagios/etc/nrpe.cfg~ |
1 |
# nano /usr/local/nagios/etc/nrpe.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
log_facility=daemon pid_file=/var/run/nrpe.pid server_port=5666 #server_address=127.0.0.1 nrpe_user=nagios nrpe_group=nagios allowed_hosts=127.0.0.1, 192.168.1.101 dont_blame_nrpe=1 allow_bash_command_substitution=0 debug=0 command_timeout=10 connection_timeout=30 command[check_users]=/usr/lib/nagios/plugins/check_users -w $ARG1$ -c $ARG2$ command[check_procs]=/usr/lib/nagios/plugins/check_procs -w $ARG1$ -c $ARG2$ -s <span class="crayon-sy">$</span><span class="crayon-v">ARG3</span><span class="crayon-sy">$</span> command[check_load]=/usr/lib/nagios/plugins/check_load -w $ARG1$ -c $ARG2$ command[check_swap]=/usr/lib/nagios/plugins/check_swap -w $ARG1$ -c $ARG2$ command[check_disk]=/usr/lib/nagios/plugins/check_disk -w $ARG1$ -c $ARG2$ -p $ARG3$ |
Сделаем символьную ссылку
1 |
# ln -s /usr/local/nagios/libexec/check_nrpe /usr/lib/nagios/plugins/ |
1 |
# ls -l /usr/lib/nagios/plugins/check_nrpe |
1 |
lrwxrwxrwx 1 root root 36 Jan 8 19:58 /usr/lib/nagios/plugins/check_nrpe -> /usr/local/nagios/libexec/check_nrpe |
1 |
# systemctl restart xinetd |
Добавим несколько проверок удаленных клиентов через nrpe на Nagios-сервере
1 |
# nano /usr/local/nagios/etc/services.d/services.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
define service{ hostgroup_name myproject-remote-servers use service-template service_description Root Partition check_command check-disk!20%!10%!/ } define service{ hostgroup_name myproject-remote-servers use service-template service_description Current Load check_command check-load!5.0,4.0,3.0!7.0,6.0,4.0 } define service{ hostgroup_name myproject-remote-servers use service-template service_description Swap Usage check_command check-swap!20!10 } define service{ hostgroup_name myproject-remote-servers use service-template service_description NRPE check_command check-nrpe-alive } |
Добавим опиcание новых команд(check-disk, check-load, check-swap, check-nrpe-alive) с использованием check_nrpe
1 |
# nano /usr/local/nagios/etc/commands.d/commands.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
define command { command_name check-swap command_line $USER1$/check_nrpe -t 30 -H $HOSTADDRESS$ -c check_swap -a $ARG1$ $ARG2$ } define command { command_name check-load command_line $USER1$/check_nrpe -t 30 -H $HOSTADDRESS$ -c check_load -a $ARG1$ $ARG2$ } define command { command_name check-disk command_line $USER1$/check_nrpe -t 30 -H $HOSTADDRESS$ -c check_disk -a $ARG1$ $ARG2$ $ARG3$ } define command { command_name check-nrpe-alive command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -u -t 15 } |
6.Установка NRPE на Nagios-сервере
1 |
# cd /tmp |
1 |
# wget http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz |
1 |
# tar xvf nrpe-*.tar.gz |
1 |
# cd nrpe-* |
1 |
# ./configure --enable-command-args --with-nagios-user=nagios --with-nagios-group=nagios --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu |
1 |
# make all |
1 |
# make install |
1 |
# apt-get install xinetd |
1 |
# make install-xinetd |
1 |
# make install-daemon-config |
1 |
# nano /etc/xinetd.d/nrpe |
1 |
only_from = 127.0.0.1 192.168.1.101 |
1 |
# service xinetd restart |
1 |
# netstat -nlptu | grep 5666 |
1 |
tcp 0 0 0.0.0.0:5666 0.0.0.0:* LISTEN 12980/xinetd |
Проверяем наличие check_nrpe бинарника
1 |
# ls -l /usr/local/nagios/libexec/check_nrpe |
1 |
-rwxrwxr-x 1 nagios nagios 91794 Jan 8 21:27 /usr/local/nagios/libexec/check_nrpe |
Проверяем синтаксис Nagios и перезапускаем Nagios
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg |
1 |
# systemctl restart nagios |
Более полное описание Nagios-проверок были представлены в другой статье
https://kamaok.org.ua/?p=1447
Перенос Nagios на отдельный домен/виртуальный хост(nagios.mydomain.com) с заменой URL http://<IP-address-server/nagios>, на nagios.mydomain.com
1 |
# nano /usr/local/nagios/etc/cgi.cfg |
1 2 |
#url_html_path=/nagios url_html_path=/ |
1 |
# nano /etc/apache2/sites-enabled/0000-nagios4.conf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<VirtualHost *:80> ServerName nagios.mydomain.com ServerAlias www.nagios.mydomain.com DocumentRoot /usr/local/nagios/share ErrorLog /var/log/apache2/nagios.mydomain.com-error.log CustomLog /var/log/apache2/nagios.mydomain.com-access.log combined ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin" ###Эту строку нужно добавить,чтобы карта Nagios(Map) корректно работала ScriptAlias /cgi-bin "/usr/local/nagios/sbin" <Directory "/usr/local/nagios/sbin"> # SSLRequireSSL Options ExecCGI AllowOverride None <IfVersion >= 2.3> <RequireAll> Require all granted # Require host 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </RequireAll> </IfVersion> <IfVersion < 2.3> Order allow,deny Allow from all # Order deny,allow # Deny from all # Allow from 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </IfVersion> </Directory> #Alias /nagios "/usr/local/nagios/share" <Directory "/usr/local/nagios/share"> # SSLRequireSSL Options None AllowOverride None <IfVersion >= 2.3> <RequireAll> Require all granted # Require host 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </RequireAll> </IfVersion> <IfVersion < 2.3> Order allow,deny Allow from all # Order deny,allow # Deny from all # Allow from 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </IfVersion> </Directory> </VirtualHost> |
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg && service nagios reload |
1 |
# apache2ctl configtest && service apache2 restart |
Настройка принудительного перенаправления с http на https (иcпользуются сертификаты от Let’s Encrypt)(Использование Let’s Encrypt)
1 |
# nano /etc/apache2/sites-enabled/0000-nagios4.conf |
1 2 3 4 5 |
… RewriteEngine on RewriteCond %{SERVER_NAME} =nagios.mydomain.com [OR] RewriteCond %{SERVER_NAME} =www.nagios.mydomain.com RewriteRule ^ https://nagios.mydomain.com%{REQUEST_URI} [END,QSA,R=permanent] |
1 |
# nano /etc/apache2/sites-enabled/0000-nagios4-ssl.conf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<IfModule mod_ssl.c> <VirtualHost *:443> ServerName nagios.mydomain.com ServerAlias www.nagios.mydomain.com DocumentRoot /usr/local/nagios/share CustomLog /var/log/apache2/nagios.mydomain.com-access.log combined SSLCertificateFile /etc/letsencrypt/live/nagios.mydomain.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/nagios.mydomain.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/nagios.mydomain.com/chain.pem SSLEngine on # Intermediate configuration, tweak to your needs SSLProtocol all -SSLv2 -SSLv3 SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA SSLHonorCipherOrder on SSLCompression off SSLOptions +StrictRequire # Add vhost name to log entries: LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" vhost_combined LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost_common ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin" ScriptAlias /cgi-bin "/usr/local/nagios/sbin" <Directory "/usr/local/nagios/sbin"> # SSLRequireSSL Options ExecCGI AllowOverride None <IfVersion >= 2.3> <RequireAll> Require all granted # Require host 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </RequireAll> </IfVersion> <IfVersion < 2.3> Order allow,deny Allow from all AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </IfVersion> </Directory> #Alias /nagios "/usr/local/nagios/share" <Directory "/usr/local/nagios/share"> # SSLRequireSSL Options None AllowOverride None <IfVersion >= 2.3> <RequireAll> Require all granted # Require host 127.0.0.1 AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </RequireAll> </IfVersion> <IfVersion < 2.3> Order allow,deny Allow from all AuthName "Nagios Access" AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-user </IfVersion> </Directory> </VirtualHost> </IfModule> |