Bacula – пакет программ архитектуры «клиент-сервер» с открытым исходным кодом, предназначенный для создания резервных копий данных, находящихся на компьютерах с различными операционными системами, для восстановления и проверки хранящихся данных. Этот пакет имеет модульную архитектуру, легко масштабируется и может быть использован, как для небольшой локальной сети из нескольких компьютеров, так и для сети предприятия, состоящего из […]
Архивы рубрики ‘Centos’
Настройка резервного копирования с помощью Bash-скриптов
1.Резервное копирование файлов (сайты, конфигурационные файлы)
1 |
# chown root:root /usr/local/scripts/backup-files-shell.sh |
1 |
# chmod 751 /usr/local/scripts/backup-files-shell.sh |
1 |
# nano /usr/local/scripts/backup-files-shell.sh |
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 |
#!/bin/bash # Формат даты DATE="$(date +%Y-%m-%d)" # Каталог для хранения бекапов STORAGEDIR="/backup" # Список сайтов для копирования SITES='/home/users' # Список катадогов,исключенных из бекапа EXCLUDE1="/home/users/<user_to_exclude>" EXCLUDE2="/home/users/<username>/<sitename>/<folder_to_exclude>" #Cписок конфигурационных файлов и других служебных файлов(Nagios,Cacti,Munin) CONFIGS='/etc /usr/local/nagios /usr/lib64/nagios/plugins /usr/share/cacti /var/lib/cacti /var/www/html' # Журналируем ошибки в файл LOGFILE="/var/log/backup.log" # Как долго(кол-во дней) хранить бекапы LIMITTIME="+14" NICE="$(which nice)" IONICE="$(which ionice)" TAR="$(which tar)" FIND="$(which find)" RM="$(which rm)" ECHO="$(which echo)" [ ! -d $STORAGEDIR/sites ] && mkdir -p $STORAGEDIR/sites [ ! -d $STORAGEDIR/configs ] && mkdir -p $STORAGEDIR/configs $NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/sites/sites-${DATE}.tar.gz $SITES --exclude=$EXCLUDE1 --exclude=$EXCLUDE2 exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Backup sites is failed - $DATE" | tee -a $LOGFILE fi $NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/configs/configs-${DATE}.tar.gz $CONFIGS exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Backup configs is failed - $DATE" | tee -a $LOGFILE fi $NICE -n 19 $IONICE -c2 -n7 $TAR -cf $STORAGEDIR/backup-files-${DATE}.tar $STORAGEDIR/sites/*.tar.gz $STORAGEDIR/configs/*.tar.gz exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Tar sites and configs is failed - $DATE" | tee -a $LOGFILE else $RM -rf $STORAGEDIR/sites/* $STORAGEDIR/configs/* $ECHO "Backup Sites and Configs is done! Backup up to $DATE " | tee -a $LOGFILE fi # Удаляем бекапы старше 14 дней $FIND $STORAGEDIR -maxdepth 1 -type f -name '*.tar' -mtime $LIMITTIME -exec $RM -rf {} \; |
2.Резервное копирование баз данных
1 |
# chown root:root /usr/local/scripts/backup-databases-shell.sh |
1 |
# chmod 751 /usr/local/scripts/backup-databases-shell.sh |
1 |
# nano /usr/local/scripts/backup-databases-shell.sh |
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 |
#!/bin/bash # Формат даты DATE="$(date +"%Y-%m-%d")" # Место хранения бекапов STORAGEDIR='/backup' # Пользователь,пароль,хост для подключения MUSER="root" MPASS="123" MHOST="localhost" # Журналируем ошибки и успешное выполнение бекапа в файл LOGFILE="/var/log/backup.log" # Как долго(кол-во дней) хранить бекапы LIMITTIME="+14" MYSQL="$(which mysql)" MYSQLDUMP="$(which mysqldump)" NICE="$(which nice)" IONICE="$(which ionice)" GZIP="$(which gzip)" TAR="$(which tar)" FIND="$(which find)" MKDIR="$(which mkdir)" ECHO="$(which echo)" RM="$(which rm)" [ ! -d $STORAGEDIR/mysql ] && $MKDIR -p $STORAGEDIR/mysql DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases' | egrep -v '(information_schema|performance_schema)')" for db in $DBS do FILE=$STORAGEDIR/mysql/$db-$DATE.sql.gz $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS -EKR --single-transaction $db | $GZIP -c > $FILE if [ ${PIPESTATUS[0]} != "0" ]; then $ECHO "Backup database is failed $db - $DATE" | tee -a $LOGFILE fi done cd $STORAGEDIR/mysql $NICE -n 19 $IONICE -c2 -n7 $TAR -cf $STORAGEDIR/backup-databases-${DATE}.tar *.sql.gz exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Tar databases is failed - $DATE" | tee -a $LOGFILE else $RM -rf $STORAGEDIR/mysql/* $ECHO "Backup Databases is done! Backup up to $DATE " | tee -a $LOGFILE fi $FIND $STORAGEDIR -maxdepth 1 -type f -name '*.tar' -mtime $LIMITTIME -exec $RM -rf {} \; |
3. Резервное копирование файлов и баз данных
1 |
# chmod 751 /usr/local/scripts/backup-all-shell.sh |
1 |
# chown root:root /usr/local/scripts/backup-all-shell.sh |
1 |
# nano /usr/local/scripts/backup-all-shell.sh |
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 |
#!/bin/bash # Формат даты DATE="$(date +%Y-%m-%d)" # Каталог для хранения бекапов STORAGEDIR="/backup" # Список сайтов для копирования SITES='/home/users' EXCLUDE1="/home/users/<user_to_exclude>" EXCLUDE2="/home/users/<username>/<sitename>/<folder_to_exclude>" #Cписок конфигурационных файлов и других служебных файлов(Nagios,Cacti,Munin) CONFIGS='/etc /usr/local/nagios /usr/lib64/nagios/plugins /usr/share/cacti /var/lib/cacti /var/www/html' # Журналируем ошибки и успешное выполнение бекапа в файл LOGFILE="/var/log/backup.log" # Как долго(кол-во дней) хранить бекапы LIMITTIME="+14" # guess binary names MYSQL="$(which mysql)" MYSQLDUMP="$(which mysqldump)" NICE="$(which nice)" IONICE="$(which ionice)" GZIP="$(which gzip)" TAR="$(which tar)" FIND="$(which find)" MKDIR="$(which mkdir)" ECHO="$(which echo)" RM="$(which rm)" # Пользователь,пароль,хост для подключения MUSER="root" MPASS="123" MHOST="localhost" [ ! -d $STORAGEDIR/sites ] && $MKDIR -p $STORAGEDIR/sites [ ! -d $STORAGEDIR/configs ] && $MKDIR -p $STORAGEDIR/configs [ ! -d $STORAGEDIR/mysql ] && $MKDIR -p $STORAGEDIR/mysql $NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/sites/sites-${DATE}.tar.gz $SITES --exclude=$EXCLUDE1 --exclude=$EXCLUDE2 exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Backup sites is failed - $DATE" | tee -a $LOGFILE fi $NICE -n 19 $IONICE -c2 -n7 $TAR -czf $STORAGEDIR/configs/configs-${DATE}.tar.gz $CONFIGS exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Backup configs is failed - $DATE" | tee -a $LOGFILE fi DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases' | egrep -v '(information_schema|performance_schema)')" for db in $DBS do FILE=$STORAGEDIR/mysql/$db-${DATE}.sql.gz $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS -EKR --single-transaction $db | $GZIP -c > $FILE if [ ${PIPESTATUS[0]} != "0" ]; then $ECHO "Backup database is failed $db - $DATE" | tee -a $LOGFILE fi done $NICE -n 19 $IONICE -c2 -n7 $TAR -cf $STORAGEDIR/backup-all-${DATE}.tar $STORAGEDIR/sites/*.tar.gz $STORAGEDIR/configs/*.tar.gz $STORAGEDIR/mysql/*.sql.gz exitcode=$? if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then $ECHO "Tar sites,config,databases is failed - $DATE" | tee -a $LOGFILE else $RM -rf $STORAGEDIR/sites/* $STORAGEDIR/configs/* $STORAGEDIR/mysql/* $ECHO "Backup sites,configs,databases is done! Backup up to $DATE " | tee -a $LOGFILE fi # Удаляем бекапы старше 14 дней $FIND $STORAGEDIR -maxdepth 1 -type f -name '*.tar' -mtime $LIMITTIME -exec $RM -rf {} \; |
Мониторинг лога с бекапом с помощью Monit/Nagios Monit(https://kamaok.org.ua/?p=361)
1 |
# nano /etc/monit.conf |
1 2 3 4 5 6 7 |
check file backup with path /var/log/backup.log if match 'Backup sites is failed' then alert if match 'Backup configs is failed' then alert if match 'Tar sites and configs is failed' then alert if match 'Tar sites,config,databases is failed' then alert if match 'Backup database is failed' then alert if match 'Tar databases is failed' then alert |
Nagios(https://kamaok.org.ua/?p=1487)
1 |
# nano /etc/nagios/log-files.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$seekfilesdir = '/var/tmp/check_logfiles'; # where the state information will be saved. $protocolsdir = '/tmp'; # where protocols with found patterns will be stored. $scriptpath = '/var/tmp'; # where scripts will be searched for. @searches = ( { tag => 'backup', logfile => '/var/log/backup.log', rotation => 'centos', warningpatterns => ['Backup sites is failed', 'Backup configs is failed', 'Tar sites and configs is failed', 'Tar sites,config,databases is failed', 'Backup database is failed', 'Tar databases is failed'], } ); |
4.Добавление в cron задания на ежедневный бекап
1 |
# nano /etc/cron.d/backup |
1 2 3 4 |
# Закомментируйте все за исключением того, что будет бекапить 10 4 * * * root /usr/local/scripts/backup-all-shell.sh > /dev/null 2>&1 # 10 4 * * * root /usr/local/scripts/backup-databases-shell.sh > /dev/null 2>&1 # 10 4 * * * root /usr/local/scripts/backup-files-shell.sh > /dev/null 2>&1 |
[…]
Настройка резервного копирования с помощью Rsnapshot
Rsnapshot, написанный на Perl, базируется на rsync. В рабочей директории программы (назовём так место, куда складываются бэкапы), создается ряд папок с индексом, который при каждом следующем запуске программы увеличивается до указанного в конфигурации значения. Затем устаревшая копия удаляется. Если пройти в любую из созданных папок, то внутри можно найти полную копию резервируемых данных. На это […]
Настройка мониторинга почтовых(mail) серверов в Nagios
1.Тестирование плагинов с командной строки
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_ssmtp -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
SSMTP OK - 0.062 second response time on <IP-address-client> port 465 [220 <IP-address-client> ESMTP Sendmail 8.14.7/8.14.7; Thu, 14 Jan 2016 18:11:04 +0200]|time=0.061593s;5.000000;10.000000;0.000000;15.000000 |
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_smtp -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
SMTP OK - 0.004 sec. response time|time=0.003644s;5.000000;10.000000;0.000000 |
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_imap -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
IMAP OK - 0.020 second response time on <IP-address-client> port 143 [* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE STARTTLS AUTH=PLAIN AUTH=LOGIN] Dovecot ready.]|time=0.020129s;5.000000;10.000000;0.000000;15.000000 |
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_simap -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
SIMAP OK - 0.059 second response time on <IP-address-client> port 993 [* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready.]|time=0.059049s;5.000000;10.000000;0.000000;15.000000 |
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_pop -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
POP OK - 0.006 second response time on <IP-address-client> port 110 [+OK Dovecot ready.]|time=0.006072s;5.000000;10.000000;0.000000;15.000000 |
1 |
# su -l nagios -c '/usr/lib64/nagios/plugins/check_spop -4 -t 15 -H <IP-address-client> -w 5 -c 10' |
1 |
SPOP OK - 0.054 second response time on <IP-address-client> port 995 [+OK Dovecot ready.]|time=0.054477s;5.000000;10.000000;0.000000;15.000000 |
2.Определение команд для проверки
1 |
# cd /usr/local/nagios/etc/ |
1 |
# nano commands.d/check-mail.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 |
define command { command_name check-plain-pop3 command_line $USER1$/check_pop -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } define command { command_name check-secure-pop3 command_line $USER1$/check_spop -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } define command { command_name check-plain-imap command_line $USER1$/check_imap -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } define command { command_name check-secure-imap command_line $USER1$/check_simap -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } define command { command_name check-plain-smtp command_line $USER1$/check_smtp -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } define command { command_name check-secure-smtp command_line $USER1$/check_ssmtp -4 -t 30 -H $HOSTADDRESS$ -w $ARG1$ -c $ARG2$ } |
3.Добавление хостов/групп на мониторинг для указанных проверок
1 |
# nano services.d/services-myproject.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 |
define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail IMAP Plain Available check_command check-plain-imap!5!10 use service-template-all-generic } define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail IMAP Secure Available check_command check-secure-imap!5!10 use service-template-all-generic } define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail POP3 Plain Available check_command check-plain-pop3!5!10 use service-template-all-generic } define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail POP3 Secure Available check_command check-secure-pop3!5!10 use service-template-all-generic } define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail SMTP Plain Available check_command check-plain-smtp!5!10 use service-template-all-generic } define service{ hostgroup_name hostgroup-myproject-all-servers service_description Mail SMTP Secure Available check_command check-secure-smtp!5!10 use service-template-all-generic } |
4.Проверка синтаксиса и перезапуск Nagios
1 |
# /etc/init.d/nagios configtest |
1 |
# /etc/init.d/nagios reload |
Настройка мониторинга лог-файлов в Nagios
1.Установка плагина для проверки лог-файлов (как на Nagios-сервере, так и на клиентском сервере)
1 |
# wget https://labs.consol.de/assets/downloads/nagios/check_logfiles-3.7.4.tar.gztar xvzf check_logfiles-3.7.4.tar.gz |
1 |
# cd check_logfiles-3.7.4/ |
1 |
# ./configure --prefix=/usr/local/nagios --with-nagios-user=nagios --with-nagios-group=nagios --with-perl=/usr/bin/perl |
1 2 3 4 5 6 7 8 |
config.status: creating t/Makefile --with-perl: /usr/bin/perl --with-gzip: /usr/bin/gzip --with-seekfiles-dir: /var/tmp/check_logfiles --with-protocols-dir: /tmp --with-trusted-path: /bin:/sbin:/usr/bin:/usr/sbin --with-nagios-user: nagios --with-nagios-group: nagios |
1 |
# make |
1 |
# make install |
1 |
# ls -al /usr/lib64/nagios/plugins/ | grep check_logfiles |
1 |
-rwxr-xr-x 1 root root 203754 Jan 14 23:12 check_logfiles |
2.Тестирование плагинов с командной строки Просмотр справки
1 |
# /usr/lib64/nagios/plugins/check_logfiles --help | less |
В самом простом случае достаточно вызвать команду с необходимыми параметрами Например
1 |
# /usr/lib64/nagios/plugins/check_logfiles -t 15 --tag=system --logfile=/var/log/messages --criticalpattern='OOM killed process' |
1 |
OK - no errors or warnings|system_lines=0 system_warnings=0 system_criticals=0 system_unknowns=0 |
Принцип работы плагина подразумевает, что проверка будет происходить первый раз полностью всего […]
Настройка мониторинга MySQL в Nagios средствами Percona Monitoring Plugins
1.Установка Percona Nagios Monitoring Plugins на Nagios-сервере (будет использоваться удаленное подключение к MySQL для снятия статистики) (в случае использования NRPE эти плагины необходимо установить на каждом клиенте, который будет мониториться)
1 |
# yum install http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1-3.noarch.rpm |
1 |
# yum install percona-nagios-plugins |
1 |
Plugins are installed to /usr/lib64/nagios/plugins |
2.Создание файла с учетными данными пользователя для удаленного доступа
1 |
# mkdir /etc/nagios/ |
1 |
# nano /etc/nagios/mysql.cnf |
1 2 3 |
[client] user = nagiosuser password = nagiospassword |
1 |
# chown root:nagios /etc/nagios/mysql.cnf |
1 |
# chmod 640 /etc/nagios/mysql.cnf |
3.Создание пользователя с необходимыми привилегиями
1 |
mysql>grant PROCESS, SUPER, REPLICATION CLIENT on *.* to nagiosuser@'<IP-address-Nagios-server>' identified by 'nagiospassword'; |
[…]
Настройка мониторинга MySQL в Nagios
1.Установка необходимых пакетов
1 |
# yum install perl-Nagios-Plugin perl-Switch |
2.Скачивание и загрузка скрипта/плагина mysql_health_check.pl в папку с плагинами(например, в /usr/lib64/nagios/plugins/) Последняя версия доступна на GitHub
1 |
https://github.com/palominodb/PalominoDB-Public-Code-Repository/tree/d94b6cef297cc9eb6a98e57390f612a0232d7c0c |
Или с моего сайта(скорее всего уже устаревшая) здесь
1 |
# chmod 755 /usr/lib64/nagios/plugins/mysql_health_check.pl |
Просмотр синтаксиса/опций
1 |
# /usr/lib64/nagios/plugins/mysql_health_check.pl --help | less |
3.Создание файла с описанием команд Первая команда — check-mysql использует стандартный/штатный скрипт, который идет в комплекте с Nagios-плагинами и отображает […]
Настройка Nagios и мониторинга Linux-хоста в Nagios
Установка Nagios описана здесь Установка Nagios на Centos Настройка Nagios и мониторинга локального Nagios-хоста (сам себя мониторит Nagios-хост)
1 |
# systemctl stop nagios |
1 |
# cd /usr/local/nagios/etc/ |
1 |
# cp cgi.cfg cgi.cfg~ |
1 |
# cp nagios.cfg nagios.cfg~ |
1 |
# cp resource.cfg resource.cfg~ |
1 |
# mv objects objects~ |
1 |
# nano 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 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 |
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 #default_user_name=guest authorized_for_system_information=nagiosadmin,myname authorized_for_configuration_information=nagiosadmin,myname authorized_for_system_commands=nagiosadmin,myname authorized_for_all_services=nagiosadmin,myname authorized_for_all_hosts=nagiosadmin,myname authorized_for_all_service_commands=nagiosadmin,myname authorized_for_all_host_commands=nagiosadmin,myname #authorized_for_read_only=user1,user2 #statusmap_background_image=smbackground.gd2 #color_transparency_index_r=255 #color_transparency_index_g=255 #color_transparency_index_b=255 default_statusmap_layout=5 default_statuswrl_layout=4 #statuswrl_include=myworld.wrl ping_syntax=/bin/ping -n -U -c 5 $HOSTADDRESS$ refresh_rate=15 result_limit=0 escape_html_tags=1 #host_unreachable_sound=hostdown.wav #host_down_sound=hostdown.wav #service_critical_sound=critical.wav #service_warning_sound=warning.wav #service_unknown_sound=warning.wav #normal_sound=noproblem.wav action_url_target=_blank notes_url_target=_blank lock_author_names=1 #enable_splunk_integration=1 #splunk_url=http://127.0.0.1:8000/ navbar_search_for_addresses=1 navbar_search_for_aliases=1 #ack_no_sticky=0 #ack_no_send=0 |
1 |
# nano resource.cfg |
1 |
$USER1$=/usr/local/nagios/libexec |
1 |
# nano 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
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 #query_socket=/usr/local/nagios/var/rw/nagios.qh lock_file=/usr/local/nagios/var/nagios.lock temp_file=/usr/local/nagios/var/nagios.tmp temp_path=/tmp event_broker_options=-1 #broker_module=/somewhere/module1.o #broker_module=/somewhere/module2.o arg1 arg2=3 debug=0 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 #global_host_event_handler=somecommand #global_service_event_handler=somecommand 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 #time_change_threshold= 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=1 #bare_update_check=0 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 #host_perfdata_command=process-host-perfdata #service_perfdata_command=process-service-perfdata #host_perfdata_file=/usr/local/nagios/var/host-perfdata #service_perfdata_file=/usr/local/nagios/var/service-perfdata #host_perfdata_file_template=[HOSTPERFDATA]\t$TIMET$\t$HOSTNAME$\t$HOSTEXECUTIO$ #service_perfdata_file_template=[SERVICEPERFDATA]\t$TIMET$\t$HOSTNAME$\t$SERVIC$ #host_perfdata_file_mode=a #service_perfdata_file_mode=a #host_perfdata_file_processing_interval=0 #service_perfdata_file_processing_interval=0 #host_perfdata_file_processing_command=process-host-perfdata-file #service_perfdata_file_processing_command=process-service-perfdata-file #host_perfdata_process_empty_results=1 #service_perfdata_process_empty_results=1 obsess_over_services=0 #ocsp_command=somecommand obsess_over_hosts=0 #ochp_command=somecommand 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 #use_timezone=US/Mountain #use_timezone=Australia/Brisbane illegal_object_name_chars=`~!$%^&*|'"<>?,()= illegal_macro_output_chars=`~$&|'"<> use_regexp_matching=0 use_true_regexp_matching=0 admin_email=my@email admin_pager=my@email daemon_dumps_core=0 use_large_installation_tweaks=0 enable_environment_macros=1 #free_child_process_memory=1 #child_processes_fork_twice=1 debug_level=0 debug_verbosity=1 debug_file=/usr/local/nagios/var/nagios.debug max_debug_file_size=10000000 allow_empty_hostgroup_assignment=0 #check_workers=3 host_down_disable_service_checks=1 |
1 |
# mkdir -p /usr/local/nagios/etc/{commands.d,contacts.d,hosts.d,services.d,misc.d} |
1 |
# chown -R nagios:nagios commands.d contacts.d hosts.d misc.d services.d |
1 |
# chmod -R 4775 commands.d contacts.d hosts.d misc.d services.d |
1 |
# chmod 600 resource.cfg |
1 |
# cp objects~/commands.cfg commands.d/notify.cfg |
1 |
# nano commands.d/notify.cfg |
1 2 3 4 5 6 7 8 9 10 11 |
# 'notify-host-email' command definition define command{ command_name notify-host-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$ } # 'notify-service-email' command definition define command{ command_name notify-service-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$ } |
1 |
# cp objects~/timeperiods.cfg misc.d/ |
1 |
# nano 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 No Time Is A Good Time } |
1 |
# nano contacts.d/contacts-template.cfg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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 } define contact { name contact-template-email use contact-template-generic host_notification_commands notify-host-email service_notification_commands notify-service-email register 0 } |
1 |
# nano contacts.d/contacts.cfg |
1 2 3 4 5 6 |
define contact { contact_name myname alias MyName MySurname email my@email use contact-template-email } |
1 |
# nano contacts.d/contactgroups-administrators.cfg |
1 2 3 4 5 |
define contactgroup { contactgroup_name all-admins alias All Administrators members myname } |
1 |
# nano 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 # flap_detection_options u process_perf_data 0 retain_status_information 1 retain_nonstatus_information 1 notification_interval 0 first_notification_delay 3 notification_period 24x7 notification_options d,u,r,f,s notifications_enabled 1 register 0 } |
1 |
# nano hosts.d/host-template-all-generic.cfg |
1 2 3 4 5 6 7 |
define host { name host-template-all-generic use host-template-generic contact_groups all-admins notification_options d,r,s register 0 } |
1 |
# nano hosts.d/hosts-myproject.cfg |
1 2 3 4 5 6 7 |
define host { host_name server.mydomain.com alias server.mydomain.com display_name server.mydomain.com address 127.0.0.1 use host-template-all-generic } |
1 |
# nano hosts.d/hostgroups-myproject.cfg |
1 2 3 4 5 |
define hostgroup { hostgroup_name hostgroup-myproject-all-servers alias All Myproject servers members server.mydomain.com } |
1 |
# nano services.d/service-template-generic.cfg |
[…]
Установка Nagios на Centos в связке с Nginx
1.Установка необходимых пакетов
1 |
# yum install gcc glibc glibc-common gd gd-devel make net-snmp unzip wget |
2. Установка Nagios 4 из исходного кода
1 |
# cd /tmp |
1 |
# wget -O nagios-4.1.1.tar.gz http://sourceforge.net/projects/nagios/files/latest/download?source=files |
1 |
# tar xvfz nagios-4.1.1.tar.gz |
Создаем пользователя и группу nagios
1 |
# useradd nagios |
Сборка и установка Nagios
1 |
# cd nagios-4.1.1/ |
1 |
# ./configure |
1 |
# make all |
1 |
# make install |
1 |
# make install-init |
1 |
# make install-config |
1 |
# make install-commandmode |
1 |
# make install-webconf |
Проверка файла конфигурации
1 |
# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg |
1 2 3 |
Total Warnings: 0 Total Errors: 0 Things look okay - No serious problems were detected during the pre-flight check |
Либо
1 |
# /etc/init.d/nagios configtest |
1 2 3 |
Total Warnings: 0 Total Errors: 0 Things look okay - No serious problems were detected during the pre-flight check |
Либо
1 |
# /etc/init.d/nagios checkconfig |
1 2 |
Running configuration check... OK. |
Расположение Nagios
1 |
# ls -l /usr/local/nagios/ |
1 2 3 4 5 6 |
drwxrwxr-x 2 nagios nagios 4096 Jan 4 15:27 bin drwxrwxr-x 3 nagios nagios 4096 Jan 4 15:28 etc drwxrwxr-x 2 nagios nagios 4096 Jan 4 15:27 libexec drwxrwxr-x 2 nagios nagios 4096 Jan 4 15:27 sbin drwxrwxr-x 14 nagios nagios 4096 Jan 4 15:27 share drwxrwxr-x 5 nagios nagios 4096 Jan 4 15:30 var |
3. Установка плагинов Nagios (предварительно необходимо […]
Настройка мониторинга MySQL в Cacti средствами Percona Monitoring Plugins
1.Копируем скрипт ss_get_mysql_stats.php в папку <path_to_Cacti>/scripts/
1 |
# cp percona-monitoring-plugins-1.1.5/cacti/scripts/ss_get_mysql_stats.php /usr/share/cacti/scripts/ |
1 |
# chmod +x /usr/share/cacti/scripts/ss_get_mysql_stats.php |
2.Разрешаем на клиенте MySQL-подключение с Cacti-сервера
1 |
# nano /etc/my.cnf |
1 2 |
#bind_address = 127.0.0.1 bind_address = 0.0.0.0 |
1 |
# service mysql restart |
1 |
# netstat -nlpt | grep mysql |
1 |
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 20359/mysqld |
Настройка firewall
1 |
# iptables -N mysql |
1 |
# iptables -A INPUT -p tcp --dport 3306 -j mysql |
1 |
# iptables -A mysql -s <IP-address-Cacti-server> -j ACCEPT |
1 |
# iptables -A mysql -j LOG --log-prefix "input mysql: " |
1 |
# iptables -A mysql -j DROP |
Или просто (подразумевается,что политика по умолчанию для цепочки INPUT установлена в DROP)
1 |
# iptables -A INPUT -p tcp --dport 3306 -s <IP-address-Cacti-server> -j ACCEPT |
Создаем пользователя с необходимыми правами, который будет подключаться с Cacti-сервера
1 |
mysql> GRANT SUPER, PROCESS ON *.* TO 'cactipercona'@'%' IDENTIFIED BY "secret"; |
1 |
mysql> flush privileges; |
3.Тестируем mysql-подключение […]