Browse Source

Initial release

master
Sergey Kalinin 9 months ago
commit
781b717abe
78 changed files with 13479 additions and 0 deletions
  1. +8
    -0
      README.md
  2. +46
    -0
      bareos/README.md
  3. +198
    -0
      bareos/Template_Bareos_Clients.xml
  4. +123
    -0
      bareos/bareos_get_all.sh
  5. +1
    -0
      check_dns_records/.gitignore
  6. +22
    -0
      check_dns_records/Dockerfile
  7. +100
    -0
      check_dns_records/README.md
  8. +14
    -0
      check_dns_records/docker-compose.yml
  9. +56
    -0
      check_dns_records/gitlab-ci.yml
  10. +26
    -0
      check_dns_records/run.sh
  11. +213
    -0
      check_dns_records/zabbix_create_host.sh
  12. +134
    -0
      check_dns_records/zabbix_dns_records_check.sh
  13. +29
    -0
      check_dns_records/zabbix_jrpc_files/host.create.json
  14. +9
    -0
      check_dns_records/zabbix_jrpc_files/host.exists.json
  15. +13
    -0
      check_dns_records/zabbix_jrpc_files/host.get.json
  16. +9
    -0
      check_dns_records/zabbix_jrpc_files/hostgroup.create.json
  17. +15
    -0
      check_dns_records/zabbix_jrpc_files/hostgroup.get.json
  18. +30
    -0
      check_dns_records/zabbix_jrpc_files/template.create.json
  19. +14
    -0
      check_dns_records/zabbix_jrpc_files/template.get.json
  20. +9
    -0
      check_dns_records/zabbix_jrpc_files/user.login.json
  21. +182
    -0
      check_dns_records/zabbix_templates/Template_DNS_Check.xml
  22. +59
    -0
      check_email_delivery/.gitlab-ci.yml
  23. +27
    -0
      check_email_delivery/Dockerfile
  24. +96
    -0
      check_email_delivery/README.md
  25. +15
    -0
      check_email_delivery/check_email_delivery-0.7.1b/CHANGES.txt
  26. +674
    -0
      check_email_delivery/check_email_delivery-0.7.1b/LICENSE.txt
  27. +77
    -0
      check_email_delivery/check_email_delivery-0.7.1b/README.txt
  28. +970
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_email_delivery
  29. +498
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_email_delivery_epn
  30. +431
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_imap_quota
  31. +235
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_imap_quota_epn
  32. +999
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_imap_receive
  33. +492
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_imap_receive_epn
  34. +782
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_smtp_send
  35. +458
    -0
      check_email_delivery/check_email_delivery-0.7.1b/check_smtp_send_epn
  36. +69
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/How to connect to IMAP server manually.txt
  37. +15
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/How to test plugin.txt
  38. +522
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_email_delivery.html
  39. +472
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_email_delivery.pod
  40. +258
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_imap_quota.html
  41. +196
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_imap_quota.pod
  42. +551
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_imap_receive.html
  43. +507
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_imap_receive.pod
  44. +375
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_smtp_send.html
  45. +324
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/check_smtp_send.pod
  46. +178
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/imap_ssl_cert.html
  47. +122
    -0
      check_email_delivery/check_email_delivery-0.7.1b/docs/imap_ssl_cert.pod
  48. +236
    -0
      check_email_delivery/check_email_delivery-0.7.1b/imap_ssl_cert
  49. +114
    -0
      check_email_delivery/check_email_delivery-0.7.1b/imap_ssl_cert_epn
  50. +63
    -0
      check_email_delivery/check_email_delivery-0.7.1b/nagios-plugins-check_email_delivery.spec
  51. +189
    -0
      check_email_delivery/check_email_send_delivery.sh
  52. +22
    -0
      check_email_delivery/docker-compose.yml
  53. +7
    -0
      check_email_delivery/email_delivery_check.cron
  54. +14
    -0
      check_email_delivery/run.sh
  55. +38
    -0
      check_email_delivery/sample.env
  56. +216
    -0
      check_email_delivery/zabbix_create_host.sh
  57. +29
    -0
      check_email_delivery/zabbix_jrpc_files/host.create.json
  58. +9
    -0
      check_email_delivery/zabbix_jrpc_files/host.exists.json
  59. +13
    -0
      check_email_delivery/zabbix_jrpc_files/host.get.json
  60. +9
    -0
      check_email_delivery/zabbix_jrpc_files/hostgroup.create.json
  61. +15
    -0
      check_email_delivery/zabbix_jrpc_files/hostgroup.get.json
  62. +30
    -0
      check_email_delivery/zabbix_jrpc_files/template.create.json
  63. +14
    -0
      check_email_delivery/zabbix_jrpc_files/template.get.json
  64. +9
    -0
      check_email_delivery/zabbix_jrpc_files/user.login.json
  65. +1407
    -0
      check_email_delivery/zabbix_templates/Template_Email_Delivery_Check.xml
  66. +13
    -0
      lxc_fs_monitoring/get_fs_status.sh
  67. +3
    -0
      lxc_fs_monitoring/zabbix_agent_user_parameter
  68. +35
    -0
      zabbix_api_use/README.md
  69. +213
    -0
      zabbix_api_use/zabbix_create_host.sh
  70. +29
    -0
      zabbix_api_use/zabbix_jrpc_files/host.create.json
  71. +9
    -0
      zabbix_api_use/zabbix_jrpc_files/host.exists.json
  72. +13
    -0
      zabbix_api_use/zabbix_jrpc_files/host.get.json
  73. +9
    -0
      zabbix_api_use/zabbix_jrpc_files/hostgroup.create.json
  74. +15
    -0
      zabbix_api_use/zabbix_jrpc_files/hostgroup.get.json
  75. +30
    -0
      zabbix_api_use/zabbix_jrpc_files/template.create.json
  76. +14
    -0
      zabbix_api_use/zabbix_jrpc_files/template.get.json
  77. +9
    -0
      zabbix_api_use/zabbix_jrpc_files/user.login.json
  78. +0
    -0
      zabbix_api_use/zabbix_templates/Some-Template.xml

+ 8
- 0
README.md View File

@ -0,0 +1,8 @@
# Что это
Набор скриптов и сервисов для мониторинга различного хозяйства в zabbix.
- bareos - мониторинг задач bareos
- check_dns_records - мониторинг состояния и изменений в любых DNS записях для любых заданных доменов
- check_email_delivery - проверка прохождения почтовых сообщений как на, так и с заданных почтовых серверов
- lxs_fs_monitoring - проверка состояния файловой системы LXS контейнеров

+ 46
- 0
bareos/README.md View File

@ -0,0 +1,46 @@
## Мониторинг Bareos в Zabbix
### bareos_get_all.sh
Скрипт для получения данных о клиентах и заданиях в Bareos для использования в zabbix.
Возможна работа как с zabbix-agent так и zabbix-sender
# Использование:
Предварительно необходимо создать узел в zabbix и прикрепить к нему шаблон Template_Bareos_Clients.xml
- Вывести список клиентов ввиде zabbix discovery JSON
```bareos_get_all.sh clients-discovery```
- Вывести список названий заданий (job) для клиента
```bareos_get_all.sh client-list-job _CLIENT_NAME_```
- Получить статусы всех заданий для клиента
```bareos_get_all.sh client-get-jobs-status _CLIENT_NAME_```
- Получить статус задания
```bareos_get_all.sh get-job-status _CLIENT_NAME_ _JOB_NAME_```
- Вывести количество задач с определенным статусом
```bareos_get_all.sh count-jobs _JOB_STATUS```
Где:
```
_CLIENT_NAME_ - имя клиента в bareos
_JOB_NAME_ - название задачи в bareos
_JOB_STATUS_ - статус задания в терминах bareos:
T - Completed successfully
E - Terminated with errors
e - Non-fatal error
f - Fatal error
W - Terminated with warnings
```
Полный список доступен тут: https://docs.bareos.org/Appendix/CatalogTables.html#jobstatus)

+ 198
- 0
bareos/Template_Bareos_Clients.xml View File

@ -0,0 +1,198 @@
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>4.0</version>
<date>2020-11-18T12:58:04Z</date>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<templates>
<template>
<template>Template_Bareos_Clients</template>
<name>Template_Bareos_Clients</name>
<description/>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<applications>
<application>
<name>Bareos clients</name>
</application>
</applications>
<items/>
<discovery_rules>
<discovery_rule>
<name>Bareos clients</name>
<type>2</type>
<snmp_community/>
<snmp_oid/>
<key>bareos.clients</key>
<delay>0</delay>
<status>0</status>
<allowed_hosts/>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<params/>
<ipmi_sensor/>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<filter>
<evaltype>0</evaltype>
<formula/>
<conditions/>
</filter>
<lifetime>30d</lifetime>
<description/>
<item_prototypes>
<item_prototype>
<name>{#BAREOSCLIENT} job {#BAREOSJOB} status</name>
<type>2</type>
<snmp_community/>
<snmp_oid/>
<key>bareos.clients.job.status[{#BAREOSCLIENT}, {#BAREOSJOB}]</key>
<delay>0</delay>
<history>90d</history>
<trends>0</trends>
<status>0</status>
<value_type>4</value_type>
<allowed_hosts/>
<units/>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<params/>
<ipmi_sensor/>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Bareos clients</name>
</application>
</applications>
<valuemap/>
<logtimefmt/>
<preprocessing/>
<jmx_endpoint/>
<timeout>3s</timeout>
<url/>
<query_fields/>
<posts/>
<status_codes>200</status_codes>
<follow_redirects>1</follow_redirects>
<post_type>0</post_type>
<http_proxy/>
<headers/>
<retrieve_mode>0</retrieve_mode>
<request_method>0</request_method>
<output_format>0</output_format>
<allow_traps>0</allow_traps>
<ssl_cert_file/>
<ssl_key_file/>
<ssl_key_password/>
<verify_peer>0</verify_peer>
<verify_host>0</verify_host>
<application_prototypes/>
<master_item/>
</item_prototype>
</item_prototypes>
<trigger_prototypes>
<trigger_prototype>
<expression>{Template_Bareos_Clients:bareos.clients.job.status[{#BAREOSCLIENT}, {#BAREOSJOB}].iregexp(&quot;.+e&quot;,#1)}=1</expression>
<recovery_mode>0</recovery_mode>
<recovery_expression/>
<name>{HOSTNAME}. Статус задания {#BAREOSJOB} для {#BAREOSCLIENT}, ERROR</name>
<correlation_mode>0</correlation_mode>
<correlation_tag/>
<url/>
<status>0</status>
<priority>3</priority>
<description/>
<type>0</type>
<manual_close>1</manual_close>
<dependencies/>
<tags/>
</trigger_prototype>
<trigger_prototype>
<expression>{Template_Bareos_Clients:bareos.clients.job.status[{#BAREOSCLIENT}, {#BAREOSJOB}].regexp(&quot;.+f&quot;,#1)}=1</expression>
<recovery_mode>0</recovery_mode>
<recovery_expression/>
<name>{HOSTNAME}. Статус задания {#BAREOSJOB} для {#BAREOSCLIENT}, FATAL ERROR</name>
<correlation_mode>0</correlation_mode>
<correlation_tag/>
<url/>
<status>0</status>
<priority>3</priority>
<description/>
<type>0</type>
<manual_close>1</manual_close>
<dependencies/>
<tags/>
</trigger_prototype>
<trigger_prototype>
<expression>{Template_Bareos_Clients:bareos.clients.job.status[{#BAREOSCLIENT}, {#BAREOSJOB}].iregexp(&quot;.+w&quot;,#1)}=1</expression>
<recovery_mode>0</recovery_mode>
<recovery_expression/>
<name>{HOSTNAME}. Статус задания {#BAREOSJOB} для {#BAREOSCLIENT}, WARNING</name>
<correlation_mode>0</correlation_mode>
<correlation_tag/>
<url/>
<status>0</status>
<priority>2</priority>
<description/>
<type>0</type>
<manual_close>1</manual_close>
<dependencies/>
<tags/>
</trigger_prototype>
</trigger_prototypes>
<graph_prototypes/>
<host_prototypes/>
<jmx_endpoint/>
<timeout>3s</timeout>
<url/>
<query_fields/>
<posts/>
<status_codes>200</status_codes>
<follow_redirects>1</follow_redirects>
<post_type>0</post_type>
<http_proxy/>
<headers/>
<retrieve_mode>0</retrieve_mode>
<request_method>0</request_method>
<allow_traps>0</allow_traps>
<ssl_cert_file/>
<ssl_key_file/>
<ssl_key_password/>
<verify_peer>0</verify_peer>
<verify_host>0</verify_host>
</discovery_rule>
</discovery_rules>
<httptests/>
<macros/>
<templates/>
<screens/>
</template>
</templates>
</zabbix_export>

+ 123
- 0
bareos/bareos_get_all.sh View File

@ -0,0 +1,123 @@
#!/bin/bash
#-------------------------------------------------------------------
# Скрипт для получения данных о клиентах и заданиях в Bareos
# для использования в zabbix.
#
# Для работы нужен шаблон Template_Bareos_Clients.xml
#-------------------------------------------------------------------
# Author: Sergey Kalinin
# https://nuk-svk.ru
# svk@nuk-svk.ru
#-------------------------------------------------------------------
# Использование:
# - Вывести список клиентов ввиде zabbix discovery JSON
# bareos_get_all.sh clients-discovery
#
# - Вывести список названий заданий (job) для клиента
# bareos_get_all.sh client-list-job _CLIENT_NAME_
#
# - Получить статусы всех заданий для клиента
# bareos_get_all.sh client-get-jobs-status _CLIENT_NAME_
#
# - Получить статус задания
# bareos_get_all.sh get-job-status _CLIENT_NAME_ _JOB_NAME_
#
# - Вывести количество задач с определенным статусом
# bareos_get_all.sh count-jobs _JOB_STATUS
#
# Где:
# _CLIENT_NAME_ - имя клиента в bareos
# _JOB_NAME_ - название задачи в bareos
# _JOB_STATUS_ - статус задания в терминах bareos:
# T - Completed successfully
# E - Terminated with errors
# e - Non-fatal error
# f - Fatal error
# W - Terminated with warnings
# (полный список доступен тут:
# https://docs.bareos.org/Appendix/CatalogTables.html#jobstatus)
#-------------------------------------------------------------------
ZABBIX_AGENT=${ZABBIX_AGENT:-FALSE}
ZABBIX_SENDER=${ZABBIX_SENDER:-/usr/bin/zabbix_sender}
ZABBIX_AGENT_CONFIG=${ZABBIX_AGNT_CONFIG:-/etc/zabbix/zabbix_agentd.conf}
ZABBIX_HOST="${ZABBIX_HOST:-bareos}"
ZABBIX_AGENT=${ZABBIX_AGENT:-FALSE}
ZABBIX_SENDER=${ZABBIX_SENDER:-/usr/bin/zabbix_sender}
ZABBIX_AGENT_CONFIG=${ZABBIX_AGNT_CONFIG:-/etc/zabbix/zabbix_agentd.conf}
ZABBIX_HOST="${ZABBIX_HOST:-bareos}"
# За сколько дней выбирать задания
JOB_AGE=2
case "$1" in
get-clients-list)
#echo "run"
echo list clients | bconsole | cut -d '|' -f 3 -s | tr -d " " | grep -E '[[:alnum:]]' | grep -E -v "^name"
;;
clients-discovery)
#CLIENTS_LIST=$(echo list clients | bconsole | cut -d '|' -f 3 -s | tr -d " " | grep -E '[[:alnum:]]' | grep -E -v "^name")
#echo "${CLIENTS_LIST}"
CLIENTS_LIST=$(${0} get-clients-list)
CLIENTS_JSON="{\"data\":["
for LINE in ${CLIENTS_LIST}; do
JOB_NAMES=$($0 client-list-jobs ${LINE})
CLIENTS_JSON="${CLIENTS_JSON}"
for NAME in ${JOB_NAMES}; do
CLIENTS_JSON="${CLIENTS_JSON} {\"{#BAREOSCLIENT}\":\"$LINE\", \"{#BAREOSJOB}\":\"$NAME\"},"
done
CLIENTS_JSON="${CLIENTS_JSON}"
done
JSON_STRING="$(echo $CLIENTS_JSON | sed 's/,\+$//') ]}"
echo "$JSON_STRING"
if [ "$ZABBIX_AGENT" = "FALSE" ]; then
$ZABBIX_SENDER -vv -c $ZABBIX_AGENT_CONFIG -s "$ZABBIX_HOST" -k bareos.clients -o "${JSON_STRING}"
fi
;;
client-list-jobs)
echo list jobs client="$2" | bconsole | awk -F "|" '{print $3}' | tr -d " " | grep -E -v "(^$)|(^name)" | sort -u
;;
client-get-jobs-status)
JOBS_LIST=$(${0} client-list-jobs ${2})
for JOB in ${JOBS_LIST}; do
${0} get-job-status ${2} ${JOB}
done
;;
get-job-status)
CLIENT=${2}
JOB_NAME=${3}
#JOB_STATUS=$(echo list job=\"${JOB_NAME}\" days=${JOB_AGE} | bconsole | awk -F "|" '{print $5 $10}' | grep -E -v "(^$)|(starttime)" | tail -1)
JOB_STATUS=$(echo list job=\"${JOB_NAME}\" client=\"${CLIENT}\" | bconsole | awk -F "|" '{print $5 $10}' | grep -E -v "(^$)|(starttime)" | tail -1)
echo "${CLIENT} ${JOB_NAME} ${JOB_STATUS}"
if [ "$ZABBIX_AGENT" = "FALSE" ]; then
$ZABBIX_SENDER -c $ZABBIX_AGENT_CONFIG -s "$ZABBIX_HOST" -k "bareos.clients.job.status[${CLIENT}, ${JOB_NAME}]" -o "${JOB_STATUS}"
fi
;;
jobs-list)
JOB_STATUS="${1}"
echo show jobs | bconsole | grep -i "^ name =" | cut -d '"' -f 2 | while read LINE; do
if [[ $JOB_STATUS != "notrun" ]]; then
echo list job=\"$LINE\" jobstatus=$JOB_STATUS | bconsole -c /etc/bareos/bconsole.conf | cut -d"|" -f10 -s | tr -d ' '| grep "^${JOB_STATUS}$" | while read RES; do
# echo list job=\"$LINE\" | bconsole -c /etc/bareos/bconsole.conf | cut -d"|" -f10 | grep "${JOB_STATUS}" | while read RES; do
if [[ -n $RES ]]
then
echo "${RES}"
fi
done
fi
done
;;
get-all)
CLIENTS_LIST=$(${0} get-clients-list)
echo "${CLIENTS_LIST}"
for CLIENT in ${CLIENTS_LIST}; do
JOB_NAMES=$($0 client-list-jobs ${CLIENT})
echo "${JOB_NAMES}"
for JOB_NAME in ${JOB_NAMES}; do
${0} get-job-status ${CLIENT} ${JOB_NAME}
done
done
;;
esac

+ 1
- 0
check_dns_records/.gitignore View File

@ -0,0 +1 @@
.env

+ 22
- 0
check_dns_records/Dockerfile View File

@ -0,0 +1,22 @@
FROM debian:buster-slim
RUN apt update -y \
&& apt install -y zabbix-agent dnsutils curl jq && \
rm -rf /var/lib/apt/lists/*
COPY zabbix_dns_records_check.sh /usr/local/bin/zabbix_dns_records_check.sh
COPY zabbix_create_host.sh /usr/local/bin/zabbix_create_host.sh
COPY run.sh /usr/local/bin/run.sh
ADD zabbix_jrpc_files/* /usr/local/lib/
COPY zabbix_templates/* /usr/local/lib/
RUN chmod 755 /usr/local/bin/*
RUN sed -i -e 's/^Server=127.0.0.1$/Server=${ZABBIX_SERVER}/' /etc/zabbix/zabbix_agentd.conf; \
sed -i -e 's/^ServerActive=127.0.0.1$/ServerActive=${ZABBIX_SERVER}/' /etc/zabbix/zabbix_agentd.conf
CMD /usr/local/bin/run.sh

+ 100
- 0
check_dns_records/README.md View File

@ -0,0 +1,100 @@
# Отслеживание изменений всех типов DNS-записей для домена
## Описание
Набор скриптов для мониторинга изменений в DNS для любого количества доменов.
Отслеживаются все записи представленные в БД DNS. Проверку можно осуществлять как просто в консоли, запуская скрипты, так и в интеграции с zabbix. Запуск сервиса может производиться как локально в системе (при помощи cron) так и ввиде docker-контейнера.
В состав сервиса входит:
- zabbix_create_host.sh - позволяет создать в zabbix группу узлов, шаблон, узел. В случае если объект уже есть, то будет получен его идентификатор. Используется Zabbix JSON RPC.
- zabbix_dns_records_check.sh - опрос DNS и получение всех типов записей с добавлением их в zabbix.
- run.sh - для запуска полного цикла проверки
- zabbix_jrpc_files - каталог содержит JSON-файлы с описанием процедур по взаимодействия с zabbix
- zabbix_templates - шаблоны zabbix
## Использование
Получения всех типов записей и создание элементов (items) в zabbix:
```zabbix_dns_records_check.sh read-json-discover```
Для получения данных по конкретному домену:
```zabbix_dns_records_check.sh domain.name.ru```
Для получения данных по конкретному домену и конкретному типу записи (A, MX, NS и т.д.):
```zabbix_dns_records_check.sh domain.name.ru MX```
Так как сервис заточен под работу с zabbix, то вышеозначенная операция сработает только в случае выставления переменной ```ZABBIX_AGENT="TRUE"```. Если значение данной переменной "FALSE", проверка будет производится сразу по всем записям и результат не будет выведен в консоль а будет отправлен в zabbix (при помощи zabbix-sender). Это правило верно и для режима "read-json-discover".
Получение всех записей для домена:
```zabbix_zimbra_domain_status.sh get-domain-records domain.name.ru```
Получение списка всех типов записей для домена:
```zabbix_zimbra_domain_status.sh get-domain-records-type domain.name.ru```
### Настройка переменных окружения для zabbix_zimbra_domain_status.sh
Список переменных с значениями по умолчанию:
```
BIN_DIR=/usr/local/bin
ETC_DIR=/usr/local/etc
# Адрес ДНС сервера
EXT_DNS=8.8.8.8
# Список доменов
DOMAIN_LIST="domain.1 domain.2 domain.n"
# Временные файлы
FILE_ZIMBRA_DOMAIN_STATUS='/tmp/domain_status'
FILE_ZIMBRA_DOMAIN_LIST='/tmp/domain_list'
# конфигурация заббикс-агента
ZABBIX_AGENT=FALSE
ZABBIX_SENDER=/usr/bin/zabbix_sender
ZABBIX_AGENT_CONFIG=/etc/zabbix/zabbix_agentd.conf
# имя узла в zabbix
ZABBIX_HOST="DNS records check"
```
### Настройка переменных окружения для zabbix_create_host.sh и значения по умолчанию
```
BIN_DIR=/usr/local/bin
ETC_DIR=/usr/local/etc
LIB_DIR=/usr/local/lib
# адрес zabbix сервера
ZABBIX_SERVER='http://zabbix.example.com'
# пользователь и пароль для доступа к zabbix-API
# по умолчанию не определены
ZABBIX_USER=
ZABBIX_PASSWORD=
# Название группы узлов в заббикс
ZABBIX_HOST_GROUP='Virtual Hosts'
# название узла в заббикс
ZABBIX_HOST="DNS records check"
# имя шаблона для прикрепления к узлу
ZABBIX_TEMPLATE_NAME="Template_DNS_Check"
```
### Запуск в Docker-контейнере
Предварительно требуется создать файл .env куда прописать имя и пароль пользователя для zabbix:
```
ZABBIX_USER=user
ZABBIX_PASSWORD=password
```
Если требуется переопеределить значения переменных то их можно либо прописать в этом-же файле либо в docker-compose.yml
Сборка контейнера в локальном репозитории:
```docker build --rm -t dns_records_check .```
Запуск осуществляется при помощи docker-compose:
```docker-compose up```
При первых запусках (2-3, связано с таймаутами в zabbix при создании новых элементов) в случае отсутствия в zabbix будут созданы: группа узлов, шаблон, узел, прикреплен к узлу шаблон.
При каждом запуске будет производится автоопределение типов DNS-записей и создание требуемых ключей (items) в заббикс (автообнаружение) для каждого домена.
Контейнер будет перезапускаться каждые 10 минут (настройка в файле run.sh).

+ 14
- 0
check_dns_records/docker-compose.yml View File

@ -0,0 +1,14 @@
version: '3'
services:
dns_check:
image: ${CONTAINER_TEST_IMAGE:-dns_records_check:debug}
env_file: .env
environment:
- ZABBIX_HOST=DNS records check
- DOMAIN_LIST=example1.com example1.org example3.ru
#- ZABBX_USER="$ZABBIX_USER"
#- ZABBIX_PASSWORD="$ZABBIX_PASSWORD"
restart: always
build:
context: .

+ 56
- 0
check_dns_records/gitlab-ci.yml View File

@ -0,0 +1,56 @@
stages:
- build
- release
- deploy
variables:
# CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
# CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest
DOCKER_DRIVER: overlay2
IMAGE_PATH: $CI_REGISTRY/$CI_PROJECT_PATH
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- mkdir -p .ci_status
.dedicated-runner: &dedicated-runner
tags:
- build1-shell
dns_check_build:
<<: *dedicated-runner
stage: build
script:
- DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker-compose build dns_check
- docker push $IMAGE_PATH/dns_records_check:dev
- touch .ci_status/dns_check_build
only:
refs:
- master
changes:
- check_dns_records/*/*.json
- check_dns_records/*/*.xml
- check_dns_records/Dockerfile
- check_dns_records/*.sh
- docker-compose.yml
artifacts:
paths:
- .ci_status/
dns_check_release:
<<: *dedicated-runner
stage: release
script:
- if [ -e .ci_status/dns_check_build ]; then docker pull $IMAGE_PATH/dns_records_check:dev; docker tag $IMAGE_PATH/dns_records_check:dev $IMAGE_PATH/dns_records_check:latest; docker push $IMAGE_PATH/dns_records_check:latest; touch .ci_status/dns_check_release; fi
artifacts:
paths:
- .ci_status/
dns_check_deploy:
<<: *dedicated-runner
stage: deploy
script:
- if [ -e .ci_status/dns_check_release ]; then docker-compose up -d --no-deps --build dns_check; fi

+ 26
- 0
check_dns_records/run.sh View File

@ -0,0 +1,26 @@
#!/bin/bash
BIN_DIR=${BIN_DIR:-/usr/local/bin}
ETC_DIR=${ETC_DIR:-/usr/local/etc}
LIB_DIR=${LIB_DIR:-/usr/local/lib}
# Check host presents into zabbix
#/usr/local/bin/zabbix_create_host.sh
echo "Creating host into zabbix"
${BIN_DIR}/zabbix_create_host.sh
echo "Creating zabbix items for host"
# Get DNS records for all domain and send them into zabbix
#/usr/local/bin/zabbix_dns_records_check.sh read-json-discover
${BIN_DIR}/zabbix_dns_records_check.sh read-json-discover
echo "Getting DNS data"
DOMAIN_LIST=${DOMAIN_LIST:-"example1.com example1.org example3.ru"}
for LINE in ${DOMAIN_LIST}; do
#/usr/local/bin/zabbix_dns_records_check.sh $LINE
${BIN_DIR}/zabbix_dns_records_check.sh $LINE
done
sleep 600

+ 213
- 0
check_dns_records/zabbix_create_host.sh View File

@ -0,0 +1,213 @@
#!/bin/bash
###################################################################
#
# Скрипт для работы с Zabbix Rest API
# Позволяет создавать группу узлов, шаблон, узел.
# Создан по мотивам
# https://www.reddit.com/r/zabbix/comments/bhdhgq/zabbix_api_example_using_just_bash_curl_and_jq/
#
# Автор: Сергей Калинин
# https://nuk-svk.ru
# svk@nuk-svk.ru
#####################################################################
#
# Использование:
# ./zabbix_create_host.sh
#
# Запуск без параметров создаст группу узлов, шаблон и узел если они
# отсутствуют. Данные берутся из переменных окружения
#####################################################################
#####################################################################
# Custom variables
BIN_DIR=${BIN_DIR:-/usr/local/bin}
ETC_DIR=${ETC_DIR:-/usr/local/etc}
LIB_DIR=${LIB_DIR:-/usr/local/lib}
zabbixServer=${ZABBIX_SERVER:-'http://zabbix.example.com'}
zabbixUsername=${ZABBIX_USER}
zabbixPassword=${ZABBIX_PASSWORD}
zabbixHostGroup=${ZABBIX_HOST_GROUP:-'Virtual Hosts'}
ZABBIX_HOST_NAME=${ZABBIX_HOST:-"DNS records check"}
ZABBIX_TEMPLATE_NAME=${ZABBIX_TEMPLATE_NAME:-"Template_DNS_Check"}
#End of custom variables
#####################################################################
header='Content-Type:application/json'
zabbixApiUrl="$zabbixServer/api_jsonrpc.php"
function exit_with_error() {
echo '********************************'
echo "$errorMessage"
echo '--------------------------------'
echo 'INPUT'
echo '--------------------------------'
echo "$json"
echo '--------------------------------'
echo 'OUTPUT'
echo '--------------------------------'
echo "$result"
echo '********************************'
exit 1
}
#####################################################################
# Auth to zabbix
# https://www.zabbix.com/documentation/3.4/manual/api/reference/user/login
function auth() {
errorMessage='*ERROR* - Unable to get Zabbix authorization token'
json=$(cat ${LIB_DIR}/user.login.json)
json=${json/USER/$zabbixUsername}
json=${json/PASSWORD/$zabbixPassword}
#echo $json
result=$(curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl)
auth=$(echo $result | jq '.result')
echo "Auth: $auth"
if [ -z "$auth" ]; then
exit_with_error
fi
echo "Login successful - Auth ID: $auth"
}
#####################################################################
# Create hostgroup
function create_host_group() {
if [ -z "$auth" ]; then
auth
fi
errorMessage="*ERROR* - Unable to create hostgroup ID for host group named '$zabbixHostGroup'"
json=`cat ${LIB_DIR}/hostgroup.create.json`
json=${json/HOSTGROUP/$zabbixHostGroup}
json=${json/AUTHID/$auth}
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
HOSTGROUP_ID=`echo $result | jq -r '.result | .groupids | .[0]'`
if [ "$HOSTGROUP_ID" == "null" ]; then
exit_with_error
fi
echo "Hostgroup '$zabbixHostGroup' was created with ID: $HOSTGROUP_ID"
}
#####################################################################
# Get hostgroup
function get_host_group() {
if [ -z "$auth" ]; then
auth
fi
errorMessage="*ERROR* - Unable to get hostgroup ID for host group named '$zabbixHostGroup'"
json=`cat ${LIB_DIR}/hostgroup.get.json`
json=${json/HOSTGROUP/$zabbixHostGroup}
json=${json/AUTHID/$auth}
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
HOSTGROUP_ID=`echo $result | jq -r '.result | .[0] | .groupid'`
if [ "$HOSTGROUP_ID" == "null" ]; then
create_host_group
fi
echo "Hostgroup ID for '$zabbixHostGroup': $HOSTGROUP_ID"
}
#####################################################################
# Create template
function create_template(){
if [ -z "$auth" ]; then
auth
fi
echo "Creating zabbix template '$ZABBIX_TEMPLATE_NAME'"
errorMessage="*ERROR* - Unable to create Template ID for '$ZABBIX_TEMPLATE_NAME'"
json=`cat ${LIB_DIR}/template.create.json`
TEMPLATE_XML=$(cat ${LIB_DIR}/$ZABBIX_TEMPLATE_NAME.xml)
TEMPLATE_XML="$(echo $TEMPLATE_XML | sed 's/"/\\"/g')"
json=${json/XMLSTRING/$TEMPLATE_XML}
json=${json/AUTHID/$auth}
#echo $json
#echo "curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl"
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
#echo $result
#exit
#RESULT=`echo $result | jq -r '.result'`
if [ "$RESULT" == "null" ]; then
exit_with_error
else
get_template
#echo "Template '$ZABBIX_TEMPLATE_NAME' was created with ID: $TEMPLATE_ID"
fi
}
#####################################################################
# Get template
function get_template(){
if [ -z "$auth" ]; then
auth
fi
errorMessage="*ERROR* - Unable to get Template ID for '$ZABBIX_TEMPLATE_NAME'"
json=`cat ${LIB_DIR}/template.get.json`
json=${json/TEMPLATE_NAME/$ZABBIX_TEMPLATE_NAME}
json=${json/AUTHID/$auth}
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
TEMPLATE_ID=`echo $result | jq -r '.result | .[0] | .templateid'`
if [ "$TEMPLATE_ID" == "null" ]; then
create_template
fi
echo "Template ID for '$ZABBIX_TEMPLATE_NAME': $TEMPLATE_ID"
}
#####################################################################
# Get host
function get_host() {
if [ -z "$auth" ]; then
auth
fi
errorMessage="*ERROR* - Unable to get host ID for host '$zabbixHost'"
json=`cat ${LIB_DIR}/host.get.json`
json=${json/HOSTNAME/$ZABBIX_HOST_NAME}
json=${json/AUTHID/$auth}
#echo $json
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
#echo $result
hostId=`echo $result | jq -r '.result | .[0] | .hostid'`
# if [ "$hostId" == "null" ]; then exit_with_error; fi
# echo "Host ID for '$zabbixHost': $hostId"
if [ "$hostId" == "null" ]; then
create_host
#exit_with_error
else
echo "Host ID for '$zabbixHost': $hostId"
fi
}
#####################################################################
# Create host
function create_host() {
if [ -z "$auth" ]; then
auth
fi
if [ -z "$TEMPLATE_ID" ]; then
get_template
fi
if [ -z "$HOSTGROUP_ID" ]; then
get_host_group
fi
echo "Create host \"$ZABBIX_HOST_NAME\""
errorMessage="*ERROR* - Host '$zabbixHost' does not created"
json=$(cat ${LIB_DIR}/host.create.json)
json=${json/HOSTNAME/$ZABBIX_HOST_NAME}
json=${json/HOSTGROUPID/$HOSTGROUP_ID}
json=${json/TEMPLATE_ID/$TEMPLATE_ID}
json=${json/AUTHID/$auth}
#echo $json
result=`curl --silent --show-error --insecure --header $header --data "$json" $zabbixApiUrl`
#echo $result
HOST_ID=`echo $result | jq -r '.result | .hostids | .[0]'`
if [ -z "$HOST_ID" ]; then
exit_with_error
else
echo "Host \"${ZABBIX_HOST_NAME}\" was created with id $HOST_ID"
fi
}
get_host

+ 134
- 0
check_dns_records/zabbix_dns_records_check.sh View File

@ -0,0 +1,134 @@
#!/bin/bash
##############################################################################
#
# Определение корректности записей в DNS
# для доменов для Zabbix
# Может работать как с zabbix-agent так и zabbix-sender
#
# Автор: Сергей Калинин
# https://nuk-svk.ru
# svk@nuk-svk.ru
##############################################################################
#
# Использование:
#
# Получение DNS записей доменов и создание JSON-файла для Zabbix:
# zabbix_zimbra_domain_status.sh discover
#
# Чтение JSON-файла и вывод на экран (в zabbix)
# zabbix_zimbra_domain_status.sh read-json-discover
#
# Получение всех записей для домена из DNS
# zabbix_zimbra_domain_status.sh get-domain-records _DOMAIN_NAME_
#
# Получение всех типов записей для домена из DNS
# zabbix_zimbra_domain_status.sh get-domain-records-type _DOMAIN_NAME_
#
# Получение ДНС записи определенного типа для домена
# zabbix_zimbra_domain_status.sh _ZIMBRA_DOMAIN_NAME_ _DNS_RECORD_TYPE_
#
# Где
# _DOMAIN_NAME_ - имя домена в DNS
# _DNS_RECORD_TYPE_ - тип DNS-записи (A, CNAME, TXT, MX, и т.д.)
#############################################################################
BIN_DIR=${BIN_DIR:-/usr/local/bin}
ETC_DIR=${ETC_DIR:-/usr/local/etc}
EXT_DNS=${EXT_DNS:-8.8.8.8}
DOMAIN_LIST=${DOMAIN_LIST:-"example1.com example1.org example3.ru"}
FILE_ZIMBRA_DOMAIN_STATUS='/tmp/domain_status'
FILE_ZIMBRA_DOMAIN_LIST='/tmp/domain_list'
ZABBIX_AGENT=${ZABBIX_AGENT:-FALSE}
ZABBIX_SENDER=${ZABBIX_SENDER:-/usr/bin/zabbix_sender}
ZABBIX_AGENT_CONFIG=${ZABBIX_AGNT_CONFIG:-/etc/zabbix/zabbix_agentd.conf}
ZABBIX_HOST="${ZABBIX_HOST:-DNS records check}"
case "$1" in
discover)
# Return a list of running services in JSON
# And create JSON-file
DOMAIN_JSON="{\"data\":["
for LINE in ${DOMAIN_LIST}; do
RECORDS_TYPE=$($0 get-domain-records-type ${LINE})
DOMAIN_JSON="${DOMAIN_JSON}"
for TYPE in ${RECORDS_TYPE}; do
DOMAIN_JSON="${DOMAIN_JSON} {\"{#DOMAIN}\":\"$LINE\", \"{#DOMAINDNSRECORD}\":\"$TYPE\"},"
done
DOMAIN_JSON="${DOMAIN_JSON}"
done
JSON_STRING="$(echo $DOMAIN_JSON | sed 's/,\+$//') ]}"
echo "${JSON_STRING}" > ${FILE_ZIMBRA_DOMAIN_LIST}.json
if [ "$ZABBIX_AGENT" = "FALSE" ]; then
$ZABBIX_SENDER -vv -c $ZABBIX_AGENT_CONFIG -s "$ZABBIX_HOST" -k domain -o "${JSON_STRING}"
fi
exit 0;
;;
read-json-discover)
# create a JSON-file for zabbix
$0 discover
# Read a JSON and return
if [ ! -f ${FILE_ZIMBRA_DOMAIN_LIST}.json ]; then
echo "File ${FILE_ZIMBRA_DOMAIN_LIST}.json not found"
exit 1
fi
while read LINE; do
echo ${LINE}
done < "${FILE_ZIMBRA_DOMAIN_LIST}.json"
;;
get-domain-records)
if [ "$2" = "" ]; then
echo "No Zimbra DOMAIN specified..."
exit 1
fi
dig @${EXT_DNS} +nocmd $2 any +noall +answer > ${FILE_ZIMBRA_DOMAIN_STATUS}
;;
get-domain-records-type)
if [ "$2" = "" ]; then
echo "No DOMAIN specified..."
exit 1
fi
$0 get-domain-records $2
cat ${FILE_ZIMBRA_DOMAIN_STATUS} | awk '{print $4}' | sort -u
;;
*)
CHECK_DOMAIN=$1
if [ "$CHECK_DOMAIN" = "" ]; then
echo "No DOMAIN specified..."
exit 1
fi
# Формируем список всех DNS-записей для домена
#dig @${EXT_DNS} +nocmd ${CHECK_DOMAIN} any +noall +answer > ${FILE_ZIMBRA_DOMAIN_STATUS}
$0 get-domain-records "${CHECK_DOMAIN}"
if [ "$ZABBIX_AGENT" = "TRUE" ]; then
# получаем данные по конкретному типу записи
# использвется при работе через zabbix-agent
RECORD_TYPE=$2
if [ "$RECORD_TYPE" = "" ]; then
echo "No DNS record type specified..."
exit 1
fi
grep -E "\s${RECORD_TYPE}\s" ${FILE_ZIMBRA_DOMAIN_STATUS} | awk '{ for(i=5; i<=NF; ++i) printf $i""FS; print "" }' | sort
else
# Формируем список типов записей для домена
#RECORD_TYPES_LIST=$(cat ${FILE_ZIMBRA_DOMAIN_STATUS} | awk '{print $4}' | sort -u)
RECORD_TYPES_LIST=$($0 get-domain-records-type "${CHECK_DOMAIN}")
for RECORD_TYPE in ${RECORD_TYPES_LIST}; do
# Запрос в DNS
#dig @${EXT_DNS} +nocmd ${RECORD_TYPE} ${CHECK_DOMAIN} +noall +answer | awk '{ for(i=5; i<=NF; ++i) printf $i""FS; print "" }' | sort
# Читаем из файла с ранее полученными данными и шлем в заббикс
#grep ${RECORD_TYPE} ${FILE_ZIMBRA_DOMAIN_STATUS} | awk '{ for(i=5; i<=NF; ++i) printf $i""FS; print "" }' | sort
$ZABBIX_SENDER -c $ZABBIX_AGENT_CONFIG -s "$ZABBIX_HOST" -k "domain.status[${CHECK_DOMAIN}, ${RECORD_TYPE}]" \
-o "$(grep -E "\s${RECORD_TYPE}\s" ${FILE_ZIMBRA_DOMAIN_STATUS} | awk '{ for(i=5; i<=NF; ++i) printf $i""FS; print "" }' | sort)"
done
fi
;;
esac
exit 0;

+ 29
- 0
check_dns_records/zabbix_jrpc_files/host.create.json View File

@ -0,0 +1,29 @@
{
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "HOSTNAME",
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": "127.0.0.1",
"dns": "",
"port": "10050"
}
],
"groups": [
{
"groupid": "HOSTGROUPID"
}
],
"templates": [
{
"templateid": "TEMPLATE_ID"
}
]
},
"auth": AUTHID,
"id": 1
}

+ 9
- 0
check_dns_records/zabbix_jrpc_files/host.exists.json View File

@ -0,0 +1,9 @@
{
"jsonrpc": "2.0",
"method": "host.exists",
"params": {
"host": "HOSTNAME"
},
"auth": AUTHID,
"id": 1
}

+ 13
- 0
check_dns_records/zabbix_jrpc_files/host.get.json View File

@ -0,0 +1,13 @@
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"filter": {
"host": [
"HOSTNAME"
]
}
},
"auth": AUTHID,
"id": 1
}

+ 9
- 0
check_dns_records/zabbix_jrpc_files/hostgroup.create.json View File

@ -0,0 +1,9 @@
{
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": "HOSTGROUP"
},
"auth": AUTHID,
"id": 1
}

+ 15
- 0
check_dns_records/zabbix_jrpc_files/hostgroup.get.json View File

@ -0,0 +1,15 @@
{
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "groupid",
"filter": {
"name": [
"HOSTGROUP"
]
}
},
"auth": AUTHID,
"id": 1
}

+ 30
- 0
check_dns_records/zabbix_jrpc_files/template.create.json View File

@ -0,0 +1,30 @@
{
"jsonrpc": "2.0",
"method": "configuration.import",
"params": {
"format": "xml",
"rules": {
"templates": {
"createMissing": true
},
"items": {
"createMissing": true
},
"discoveryRules": {
"createMissing": true
},
"triggers": {
"createMissing": true
},
"graphs": {
"createMissing": true
},
"applications": {
"createMissing": true
}
},
"source": "XMLSTRING"
},
"auth": AUTHID,
"id": 1
}

+ 14
- 0
check_dns_records/zabbix_jrpc_files/template.get.json View File

@ -0,0 +1,14 @@
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
"TEMPLATE_NAME"
]
}
},
"auth": AUTHID,
"id": 1
}

+ 9
- 0
check_dns_records/zabbix_jrpc_files/user.login.json View File

@ -0,0 +1,9 @@
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "USER",
"password": "PASSWORD"
},
"id": 1
}

+ 182
- 0
check_dns_records/zabbix_templates/Template_DNS_Check.xml View File

@ -0,0 +1,182 @@
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>4.0</version>
<date>2020-10-09T07:22:33Z</date>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<templates>
<template>
<template>Template_DNS_Check</template>
<name>Template_DNS_Check</name>
<description/>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<applications>
<application>
<name>Domain DNS Records</name>
</application>
</applications>
<items/>
<discovery_rules>
<discovery_rule>
<name>Domain Discovery</name>
<type>2</type>
<snmp_community/>
<snmp_oid/>
<key>domain</key>
<delay>0</delay>
<status>0</status>
<allowed_hosts/>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<params/>
<ipmi_sensor/>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<filter>
<evaltype>0</evaltype>
<formula/>
<conditions/>
</filter>
<lifetime>30d</lifetime>
<description/>
<item_prototypes>
<item_prototype>
<name>&quot;{#DOMAINDNSRECORD}&quot; record for &quot;{#DOMAIN}&quot;</name>
<type>2</type>
<snmp_community/>
<snmp_oid/>
<key>domain.status[{#DOMAIN}, {#DOMAINDNSRECORD}]</key>
<delay>0</delay>
<history>90d</history>
<trends>0</trends>
<status>0</status>
<value_type>4</value_type>
<allowed_hosts/>
<units/>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<params/>
<ipmi_sensor/>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Domain DNS Records</name>
</application>
</applications>
<valuemap/>
<logtimefmt/>
<preprocessing/>
<jmx_endpoint/>
<timeout>3s</timeout>
<url/>
<query_fields/>
<posts/>
<status_codes>200</status_codes>
<follow_redirects>1</follow_redirects>
<post_type>0</post_type>
<http_proxy/>
<headers/>
<retrieve_mode>0</retrieve_mode>
<request_method>0</request_method>
<output_format>0</output_format>
<allow_traps>0</allow_traps>
<ssl_cert_file/>
<ssl_key_file/>
<ssl_key_password/>
<verify_peer>0</verify_peer>
<verify_host>0</verify_host>
<application_prototypes/>
<master_item/>
</item_prototype>
</item_prototypes>
<trigger_prototypes>
<trigger_prototype>
<expression>{Template_DNS_Check:domain.status[{#DOMAIN}, {#DOMAINDNSRECORD}].nodata(20m)}=1</expression>
<recovery_mode>0</recovery_mode>
<recovery_expression/>
<name>{HOSTNAME}. Нет данных о проверке DNS зон</name>
<correlation_mode>0</correlation_mode>
<correlation_tag/>
<url/>
<status>0</status>
<priority>3</priority>
<description/>
<type>0</type>
<manual_close>0</manual_close>
<dependencies/>
<tags/>
</trigger_prototype>
<trigger_prototype>
<expression>{Template_DNS_Check:domain.status[{#DOMAIN}, {#DOMAINDNSRECORD}].diff()}=1</expression>
<recovery_mode>2</recovery_mode>
<recovery_expression/>
<name>Изменение {#DOMAINDNSRECORD}-записи для &quot;{#DOMAIN}</name>
<correlation_mode>0</correlation_mode>
<correlation_tag/>
<url/>
<status>0</status>
<priority>2</priority>
<description/>
<type>0</type>
<manual_close>1</manual_close>
<dependencies/>
<tags/>
</trigger_prototype>
</trigger_prototypes>
<graph_prototypes/>
<host_prototypes/>
<jmx_endpoint/>
<timeout>3s</timeout>
<url/>
<query_fields/>
<posts/>
<status_codes>200</status_codes>
<follow_redirects>1</follow_redirects>
<post_type>0</post_type>
<http_proxy/>
<headers/>
<retrieve_mode>0</retrieve_mode>
<request_method>0</request_method>
<allow_traps>0</allow_traps>
<ssl_cert_file/>
<ssl_key_file/>
<ssl_key_password/>
<verify_peer>0</verify_peer>
<verify_host>0</verify_host>
</discovery_rule>
</discovery_rules>
<httptests/>
<macros/>
<templates/>
<screens/>
</template>
</templates>
</zabbix_export>

+ 59
- 0
check_email_delivery/.gitlab-ci.yml View File

@ -0,0 +1,59 @@
stages:
- build
- release
- deploy
variables:
# CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
# CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest
DOCKER_DRIVER: overlay2
IMAGE_PATH: $CI_REGISTRY/$CI_PROJECT_PATH
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- mkdir -p .ci_status
.dedicated-runner: &dedicated-runner
tags:
- build1-shell
email_check_build:
<<: *dedicated-runner
stage: build
script:
- DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker-compose build email_delivery_check_mail
- docker push $IMAGE_PATH/email_delivery_check:dev
- touch .ci_status/email_check_build
only:
refs:
- master
changes:
- check_email_delivery-0.7.1b/*
- ./*/*.json
- ./*/*.xml
- Dockerfile
- *.sh
- docker-compose.yml
artifacts:
paths:
- .ci_status/
email_check_release:
<<: *dedicated-runner
stage: release
script:
- if [ -e .ci_status/email_check_build ]; then docker pull $IMAGE_PATH/email_delivery_check:dev; docker tag $IMAGE_PATH/email_delivery_check:dev $IMAGE_PATH/email_delivery_check:latest; docker push $IMAGE_PATH/email_delivery_check:latest; touch .ci_status/email_check_release; fi
artifacts:
paths:
- .ci_status/
email_check_deploy:
<<: *dedicated-runner
stage: deploy
script:
- if [ -e .ci_status/email_check_release ]; then docker-compose up -d --no-deps --build email_delivery_check_mail; docker-compose up -d --no-deps --build email_delivery_check_mail2; fi

+ 27
- 0
check_email_delivery/Dockerfile View File

@ -0,0 +1,27 @@
FROM debian:buster-slim
RUN apt-get update; apt-get install -y libnet-imap-client-perl libnet-imap-perl \
libcrypt-openssl-bignum-perl libcrypt-openssl-dsa-perl libcrypt-openssl-ec-perl \
libcrypt-openssl-pkcs10-perl libcrypt-openssl-pkcs12-perl libcrypt-openssl-random-perl \
libcrypt-openssl-rsa-perl libnet-smtp-ssl-perl libnet-smtp-tls-perl libnet-smtps-perl \
libnet-imap-client-perl zabbix-agent libmail-imapclient-perl curl jq && \
rm -rf /var/lib/apt/lists/*
COPY ./check_email_delivery-0.7.1b/check_* /usr/local/bin/
COPY ./check_email_delivery-0.7.1b/imap_* /usr/local/bin/
COPY check_email_send_delivery.sh /usr/local/bin/check_email_send_delivery.sh
COPY zabbix_create_host.sh /usr/local/bin/zabbix_create_host.sh
COPY run.sh /usr/local/bin/run.sh
ADD zabbix_jrpc_files/* /usr/local/lib/
COPY zabbix_templates/* /usr/local/lib/
RUN chmod 755 /usr/local/bin/*
RUN export RUNNING_ON_DOCKER='TRUE'
RUN sed -i -e 's/^Server=127.0.0.1$/Server=${ZABBIX_SERVER}/' /etc/zabbix/zabbix_agentd.conf; \
sed -i -e 's/^ServerActive=127.0.0.1$/ServerActive=${ZABBIX_SERVER}/' /etc/zabbix/zabbix_agentd.conf
CMD /usr/local/bin/run.sh

+ 96
- 0
check_email_delivery/README.md View File

@ -0,0 +1,96 @@
# Проверка прохождения почтовых сообщений
Набор скриптов для проведения проверок прохождения почтовых сообщений на/с почтовые сервера при помощи zabbix.
За основу взяты скрипты от nagios http://nagiosplugins.org/
Сервис можно запускать как локально по времени (cron-ом) так и в docker-контейнерах. В данном примере все конфиги представлены для запуска проверки на двух почтовых серверах.
## Описание
Для запуска проверки прохождения почты нужно запустить файл ```check_email_send_delivery.sh```
Формат команды запуска
```
check_email_send_delivery.sh METHOD MAIL_SERVER
```
Где METHOD - это тип проверки, должен быть:
* "local" - локальная проверка (внутри сети)
* "incoming" - проверка прохождения входящей почты (отправка извне)
* "outgoing" - проверка прохождения исходящей почты (отправка изнутри наружу)
MAIL_SERVER - FQDN имя почтового сервера
## Использование
Скрипт можно запускать как по времени так и ввиде docker-контейнера
### Настройка переменных окружения
Настройки для каждого почтового сервера заданы в отдельных файлах (формат имени ".FQDN.env"):
```
.mail2.exampla.com.env
.mail1.example.com.env
```
Соответствующий файл будет загружен при запуске скрипта.
### Запуск по времени
Предварительно требуется скопировать рабочие файлы, файлы настроек серверов cron-a и настроить узлы в zabbix (можно применить скрипт zabbix_create_host.sh) Для этого можно выполнить следующие команды:
```
cp check_email_send_delivery.sh /usr/local/bin/
cp check_email_delivery-0.7.1b/check_* /usr/local/bin/
cp check_email_delivery-0.7.1b/imap_* /usr/local/bin/
cp email_delivery_check.cron /etc/cron.d/email_delivery_check
cp sample.env /usr/local/etc/.mail1.example.com.env
cp sample.env /usr/local/etc/.mail2.example.com.env
source /usr/local/etc/.mail1.example.com.env
./zabbix_create_host.sh
source /usr/local/etc/.mail2.example.com.env
./zabbix_create_host.sh
```
Файлы настроек "sample.env" правятся соответсвенно проверямемым серверам. Затем перезапускаем службу crond
```systemctl restart crond```
### Запуск в Docker-контейнере
Предварительно требуется скопировать файл примерных настроек и отредактировать, согласно Вашим требованиям (FQDN полное имя вашего почтового сервера такое-же как и в docker-compose.yml)
```cp sample.env .FQDN.env```
При первом запуске контейнеров будут созданы узлы в заббикс и подключены шаблоны, при повторных запусках добавятся обнаруженные элементы данных. Это связанно с особенностями работы заббикса (временной промежуток). Данные будут поступать после 2-3 запуска контейнера.
Контейнеры запускаются автоматически раз в 5 (Check_email_delivery) минут. Настройки производятся через переменные окружения.
Перед запуском следует установить данные переменные (остальные можно оставить по умолчанию, полный список см. в docker-compose.yml):
Пользователь заббикс:
- ZABBIX_USER=
- ZABBIX_PASSWORD=
- ZABBIX_TEMPLATE_NAME=Template_Email_Delivery_Check
Почтовые аккаунты (для двух MTA используются разные ящики из-за ограничения гугла на количество сообщений в сутки):
- SENDER_EMAIL=delivery_speed@example.com
- SENDER_PASSWORD=
- RECEIVER_EMAIL=delivery_speed_local@example.com
- RECEIVER_PASSWOR=
- EXT_SENDER_EMAIL=external@gmail.com
- EXT_SENDER_PASSWORD=
- EXT_RECEIVER_EMAIL=external@gmail.com
- EXT_RECEIVER_PASSWORD=
- EXT_SENDER_EMAIL_2=external2@gmail.com
- EXT_RECEIVER_EMAIL_2=external2@gmail.com
Сборка контейнера в локальном репозитории:
```docker build --rm -t email_delivery_check .```
Проверка для каждого сервера запускается в отдельном контейнере. Запуск осуществляется при помощи docker-compose:
```docker-compose up -d```

+ 15
- 0
check_email_delivery/check_email_delivery-0.7.1b/CHANGES.txt View File

@ -0,0 +1,15 @@
2005-11-10
* published
2005-05-10
* received patches from Johan Nilsson <johann (at) axis.com>
2006-07-20
* received patches from Geoff Crompton <geoff.crompton@strategicdata.com.au>
2007-04-24
* packaged ePN version of the plugins -- the __END__ block for embedded documentation was causing an error because of the way ePN wraps the perl scripts. see http://nagios.sourceforge.net/docs/2_0/embeddedperl.html
* added SSL support using patch from Benjamin Ritcey <ben@ritcey.com>
2007-10-21
* added TLS support for SMTP using Net::SMTP::TLS
* added SSL support for SMTP using Net::SMTP::SSL, but NOTE that I don't have access to an SMTPS server so I cannot test this.
2007-12-04
* small fix with SSL support for IMAP related to bugfix in Mail::IMAPClient 3.00 over 2.2.9 thanks to Seth P. Low <low@modog.com>
* added --usage option to all three plugins for familiarity with the official nagios plugins

+ 674
- 0
check_email_delivery/check_email_delivery-0.7.1b/LICENSE.txt View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this