Restore repo

This commit is contained in:
svk 2024-11-06 10:16:00 +03:00
commit 4189fcad46
87 changed files with 14088 additions and 0 deletions

9
README.md Executable file
View File

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

46
bareos/README.md Normal file
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)

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
bareos/bareos_get_all.sh Executable file
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
check_dns_records/.gitignore vendored Executable file
View File

@ -0,0 +1 @@
.env

22
check_dns_records/Dockerfile Executable file
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
check_dns_records/README.md Executable file
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).

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: .

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:
- ./*/*.json
- ./*/*.xml
- Dockerfile
- *.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
check_dns_records/run.sh Executable file
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

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

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;

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
}

View File

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

View File

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

View File

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

View File

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

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
}

View File

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

View File

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

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>

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
check_email_delivery/Dockerfile Executable file
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
check_email_delivery/README.md Executable file
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```

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

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
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -0,0 +1,77 @@
This file was updated on Sun Oct 21 21:32:12 PDT 2007.
Developer guidelines:
http://nagiosplug.sourceforge.net/developer-guidelines.html
Nagios Plugins:
http://nagiosplugins.org/
Nagios: http://nagios.org and http://nagiosplug.sourceforge.net
Perl library: http://search.cpan.org/dist/Nagios-Plugin/lib/Nagios/Plugin.pm
The email delivery plugin I wrote uses two other plugins
(smtp send and imap receive), also included, to send a message
to an email account and then check that account for the message
and delete it. The plugin times how long it takes for the
message to be delivered and the warning and critical thresholds
are for this elapsed time.
A few notes:
1. I tried to use the check_smtp plugin for sending mail. I
can do it on the command line but I can't get the newlines to
happen from the nagios config file (\n doesn't seem to work so smtp
server waits for the '.' but doesn't get it like it does when I
use single quote and newlines from the command line). So if
you know how to get the check_smtp plugin to send a message from
the nagios config, that one could be used instead of the
check_smtp_send plugin included here (and please let me know)
2. I looked at check_mail.pl by bledi51 and its pretty good,
and also conforms better to nagios perl plugin guidelnes than
mine does. So I'm going to be revising my plugins to conform
more.
Finally, usage example from my own nagios config:
define command{
command_name check_email_delivery
command_line $USER1$/check_email_delivery -H $HOSTADDRESS$ --mailfrom $ARG3$ --mailto $ARG4$ --username $ARG5$ --password $ARG6$ --libexec $USER1$ -w $ARG1$ -c $ARG2$
}
define service{
use generic-service
host_name mail.your.net
service_description EMAIL DELIVERY
check_command check_email_delivery!5!120!sender@your.net!recipient@your.net!recipient@your.net!password
}
A new usage example equivalent to the old one but using the new --plugins and --token options:
define command{
command_name check_email_delivery
command_line $USER1$/check_email_delivery -p '$USER1$/check_smtp_send -H $HOSTADDRESS$ --mailfrom $ARG3$ --mailto $ARG4$ -U $ARG5$ -P $ARG6$ --subject "Nagios %TOKEN1%" -w $ARG1$ -c $ARG2$' -p '$USER1$/check_imap_receive -H $HOSTADDRESS$ -U $ARG5$ -P $ARG6$ -s SUBJECT -s "Nagios %TOKEN1%" -w $ARG1$ -c $ARG2$' -w $ARG1$,$ARG1$ -c $ARG2$,$ARG2$
}
define service{
use generic-service
host_name mail.your.net
service_description EMAIL DELIVERY
check_command check_email_delivery!5!120!sender@your.net!recipient@your.net!recipient@your.net!password
}
References to similar plugins:
pop3(s) email matching plugin by kkvenkit
check_mail.pl by bledi51
check_email_loop.pl by ryanwilliams
check_pop.pl and check_imap.pl by http://www.jhweiss.de/software/nagios.html

View File

@ -0,0 +1,970 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.7.1';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $host = "";
my $smtp_server = "";
my $smtp_port = "";
my $imap_server = "";
my $smtp_username = "";
my $smtp_password = "";
my $smtp_tls = "";
my $imap_port = "";
my $imap_username = "";
my $imap_password = "";
my $imap_mailbox = "";
my $username = "";
my $password = "";
my $ssl = "";
my $imap_ssl = "";
my $mailto = "";
my $mailfrom = "";
my @header = ();
my $body = "";
my $warnstr = "";
my $critstr = "";
my $waitstr = "";
my $delay_warn = 95;
my $delay_crit = 300;
my $smtp_warn = 15;
my $smtp_crit = 30;
my $imap_warn = 15;
my $imap_crit = 30;
my $timeout = "";
my @alert_plugins = ();
my $imap_interval = 5;
my $imap_retries = 5;
my @plugins = ();
my @token_formats = ();
my $tokenfile = "";
my $default_crit = 30;
my $default_warn = 15;
my $default_wait = 5;
my $default_timeout = 60;
my $time_hires = "";
my $libexec = "/usr/local/nagios/libexec";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=s"=>\$warnstr,"c|critical=s"=>\$critstr, "t|timeout=s"=>\$timeout,
"libexec=s"=>\$libexec,
# plugin settings
"p|plugin=s"=>\@plugins, "T|token=s"=>\@token_formats,
"A|alert=i"=>\@alert_plugins,
"F|file=s"=>\$tokenfile,
# common settings
"H|hostname=s"=>\$host,
"U|username=s"=>\$username,"P|password=s"=>\$password,
"ssl!"=>\$ssl,
# smtp settings
"smtp-server=s"=>\$smtp_server,"smtp-port=i"=>\$smtp_port,
"mailto=s"=>\$mailto, "mailfrom=s",\$mailfrom,
"header=s"=>\@header, "body=s"=>\$body,
# smtp-tls settings
"smtptls!"=>\$smtp_tls,
"smtp-username=s"=>\$smtp_username,"smtp-password=s"=>\$smtp_password,
# delay settings
"wait=s"=>\$waitstr,
# imap settings
"imap-server=s"=>\$imap_server,"imap-port=i"=>\$imap_port,
"imap-username=s"=>\$imap_username,"imap-password=s"=>\$imap_password,
"imap-mailbox=s"=>\$imap_mailbox,
"imap-check-interval=i"=>\$imap_interval,"imap-retries=i"=>\$imap_retries,
"imapssl!"=>\$imap_ssl,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Warning threshold: $delay_warn seconds\n";
print "Critical threshold: $delay_crit seconds\n";
print "Default wait: $default_wait seconds\n";
print "Default timeout: $default_timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $host ) {
$smtp_server = $host if $smtp_server eq "";
$imap_server = $host if $imap_server eq "";
}
if( $username ) {
$smtp_username = $username if $smtp_username eq "";
$imap_username = $username if $imap_username eq "";
}
if( $password ) {
$smtp_password = $password if $smtp_password eq "";
$imap_password = $password if $imap_password eq "";
}
if( $ssl ) {
$imap_ssl = $ssl if $imap_ssl eq "";
$smtp_tls = $ssl if $smtp_tls eq "";
}
if( $help_usage
||
(
scalar(@plugins) == 0
&&
(
$smtp_server eq "" || $mailto eq "" || $mailfrom eq ""
|| $imap_server eq "" || $username eq "" || $password eq ""
)
)
) {
print "Usage 1: $0 -H host \n\t".
"--mailto recipient\@your.net --mailfrom sender\@your.net --body 'message' \n\t".
"--username username --password password \n\t".
"[-w <seconds>] [-c <seconds>]\n\t" .
"[--imap-check-interval <seconds> ] [--imap-retries <times> ]\n";
print "Usage 2: $0 \n\t".
"-p 'first plugin command with %TOKEN1% embedded' \n\t".
"-p 'second plugin command with %TOKEN1% embedded' \n\t".
"[-w <seconds1>,<seconds2>] [-c <seconds1>,<seconds2>] \n";
exit $status{UNKNOWN};
}
# determine thresholds
my @warning_times = split(",", $warnstr);
my @critical_times = split(",", $critstr);
my @alarm_times = split(",", $timeout);
my @wait_times = split(",", $waitstr);
my ($dw,$sw,$rw) = split(",", $warnstr);
my ($dc,$sc,$rc) = split(",", $critstr);
my ($wait) = split(",", $waitstr);
$delay_warn = $dw if defined $dw and $dw ne "";
$smtp_warn = $sw if defined $sw and $sw ne "";
$imap_warn = $rw if defined $rw and $rw ne "";
$delay_crit = $dc if defined $dc and $dc ne "";
$smtp_crit = $sc if defined $sc and $sc ne "";
$imap_crit = $rc if defined $rc and $rc ne "";
my $smtp_thresholds = "";
$smtp_thresholds .= "-w $smtp_warn " if defined $smtp_warn and $smtp_warn ne "";
$smtp_thresholds .= "-c $smtp_crit " if defined $smtp_crit and $smtp_crit ne "";
my $imap_thresholds = "";
$imap_thresholds .= "-w $imap_warn " if defined $imap_warn and $imap_warn ne "";
$imap_thresholds .= "-c $imap_crit " if defined $imap_crit and $imap_crit ne "";
$imap_thresholds .= "--imap-check-interval $imap_interval " if defined $imap_interval and $imap_interval ne "";
$imap_thresholds .= "--imap-retries $imap_retries " if defined $imap_retries and $imap_retries ne "";
if( scalar(@alarm_times) == 1 ) {
$default_timeout = shift(@alarm_times);
}
# determine which other options to include
my $smtp_options = "";
$smtp_options .= "-H $smtp_server " if defined $smtp_server and $smtp_server ne "";
$smtp_options .= "-p $smtp_port " if defined $smtp_port and $smtp_port ne "";
$smtp_options .= "--tls " if defined $smtp_tls and $smtp_tls;
$smtp_options .= "-U ".shellquote($smtp_username)." " if defined $smtp_username and $smtp_username ne "";
$smtp_options .= "-P ".shellquote($smtp_password)." " if defined $smtp_password and $smtp_password ne "";
$smtp_options .= "--mailto ".shellquote($mailto)." " if defined $mailto and $mailto ne "";
$smtp_options .= "--mailfrom ".shellquote($mailfrom)." " if defined $mailfrom and $mailfrom ne "";
foreach my $h( @header ) {
$smtp_options .= "--header ".shellquote($h)." ";
}
my $imap_options = "";
$imap_options .= "-H $imap_server " if defined $imap_server and $imap_server ne "";
$imap_options .= "-p $imap_port " if defined $imap_port and $imap_port ne "";
$imap_options .= "-U ".shellquote($imap_username)." " if defined $imap_username and $imap_username ne "";
$imap_options .= "-P ".shellquote($imap_password)." " if defined $imap_password and $imap_password ne "";
$imap_options .= "--mailbox ".shellquote($imap_mailbox)." " if defined $imap_mailbox and $imap_mailbox ne "";
$imap_options .= "--ssl " if defined $imap_ssl and $imap_ssl;
# create the report object
my $report = new PluginReport;
my @report_plugins = (); # populated later with either (smtp,imap) or (plugin1,plugin2,...)
my $time_start; # initialized later with time the work actually starts
# create token formats for use with the plugins
my @alpha = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z/;
my @numeric = qw/0 1 2 3 4 5 6 7 8 9/;
my @hex = qw/0 1 2 3 4 5 6 7 8 9 a b c d e f/;
my @pgp_even = qw/aardvark absurd accrue acme adrift adult afflict ahead aimless Algol allow alone ammo ancient apple artist assume Athens atlas Aztec baboon backfield backward banjo beaming bedlamp beehive beeswax befriend Belfast berserk billiard bison blackjack blockade blowtorch bluebird bombast bookshelf brackish breadline breakup brickyard briefcase Burbank button buzzard cement chairlift chatter checkup chisel choking chopper Christmas clamshell classic classroom cleanup clockwork cobra commence concert cowbell crackdown cranky crowfoot crucial crumpled crusade cubic dashboard deadbolt deckhand dogsled dragnet drainage dreadful drifter dropper drumbeat drunken Dupont dwelling eating edict egghead eightball endorse endow enlist erase escape exceed eyeglass eyetooth facial fallout flagpole flatfoot flytrap fracture framework freedom frighten gazelle Geiger glitter glucose goggles goldfish gremlin guidance hamlet highchair hockey indoors indulge inverse involve island jawbone keyboard kickoff kiwi klaxon locale lockup merit minnow miser Mohawk mural music necklace Neptune newborn nightbird Oakland obtuse offload optic orca payday peachy pheasant physique playhouse Pluto preclude prefer preshrunk printer prowler pupil puppy python quadrant quiver quota ragtime ratchet rebirth reform regain reindeer rematch repay retouch revenge reward rhythm ribcage ringbolt robust rocker ruffled sailboat sawdust scallion scenic scorecard Scotland seabird select sentence shadow shamrock showgirl skullcap skydive slingshot slowdown snapline snapshot snowcap snowslide solo southward soybean spaniel spearhead spellbind spheroid spigot spindle spyglass stagehand stagnate stairway standard stapler steamship sterling stockman stopwatch stormy sugar surmount suspense sweatband swelter tactics talon tapeworm tempest tiger tissue tonic topmost tracker transit trauma treadmill Trojan trouble tumor tunnel tycoon uncut unearth unwind uproot upset upshot vapor village virus Vulcan waffle wallet watchword wayside willow woodlark Zulu/;
my @pgp_odd = qw/adroitness adviser aftermath aggregate alkali almighty amulet amusement antenna applicant Apollo armistice article asteroid Atlantic atmosphere autopsy Babylon backwater barbecue belowground bifocals bodyguard bookseller borderline bottomless Bradbury bravado Brazilian breakaway Burlington businessman butterfat Camelot candidate cannonball Capricorn caravan caretaker celebrate cellulose certify chambermaid Cherokee Chicago clergyman coherence combustion commando company component concurrent confidence conformist congregate consensus consulting corporate corrosion councilman crossover crucifix cumbersome customer Dakota decadence December decimal designing detector detergent determine dictator dinosaur direction disable disbelief disruptive distortion document embezzle enchanting enrollment enterprise equation equipment escapade Eskimo everyday examine existence exodus fascinate filament finicky forever fortitude frequency gadgetry Galveston getaway glossary gossamer graduate gravity guitarist hamburger Hamilton handiwork hazardous headwaters hemisphere hesitate hideaway holiness hurricane hydraulic impartial impetus inception indigo inertia infancy inferno informant insincere insurgent integrate intention inventive Istanbul Jamaica Jupiter leprosy letterhead liberty maritime matchmaker maverick Medusa megaton microscope microwave midsummer millionaire miracle misnomer molasses molecule Montana monument mosquito narrative nebula newsletter Norwegian October Ohio onlooker opulent Orlando outfielder Pacific pandemic Pandora paperweight paragon paragraph paramount passenger pedigree Pegasus penetrate perceptive performance pharmacy phonetic photograph pioneer pocketful politeness positive potato processor provincial proximate puberty publisher pyramid quantity racketeer rebellion recipe recover repellent replica reproduce resistor responsive retraction retrieval retrospect revenue revival revolver sandalwood sardonic Saturday savagery scavenger sensation sociable souvenir specialist speculate stethoscope stupendous supportive surrender suspicious sympathy tambourine telephone therapist tobacco tolerance tomorrow torpedo tradition travesty trombonist truncated typewriter ultimate undaunted underfoot unicorn unify universe unravel upcoming vacancy vagabond vertigo Virginia visitor vocalist voyager warranty Waterloo whimsical Wichita Wilmington Wyoming yesteryear Yucatan/;
my %formats = (
'a' => sub { pick_random(@alpha) },
'n' => sub { pick_random(@numeric) },
'c' => sub { pick_random(@alpha,@numeric) },
'h' => sub { pick_random(@hex) },
'U' => sub { time },
'X' => sub { pick_random(@pgp_even) },
'Y' => sub { pick_random(@pgp_odd) },
);
if( scalar(@plugins) ) {
# scan the plugin commands for use of tokens to count how many we need
my $token_count = 0;
foreach my $p (@plugins) {
my @matches = sort ($p =~ m/%TOKEN(\d+)%/g);
my $max = pop @matches;
$token_count = $max if defined($max) && $max > $token_count;
}
# create the tokens
my @tokens = ();
foreach my $t (1..$token_count) {
my $format = shift @token_formats;
$format = "U-X-Y" unless $format;
my @format_characters = split(//, $format);
my $token = "";
foreach my $c (@format_characters) {
if( defined $formats{$c} ) {
$token .= &{$formats{$c}};
}
else {
$token .= $c;
}
}
push @tokens, $token;
}
# substitute the tokens into each plugin command
foreach my $p (@plugins) {
foreach my $t (1..$token_count) {
my $token = $tokens[$t-1];
$p =~ s/%TOKEN$t%/$token/g;
}
}
# mark plugins that are allowed to generate alerts. default behavior is to alert for all plugins.
my %alert_plugins = ();
if( scalar(@alert_plugins) > 0 ) {
%alert_plugins = map { $_ => 1 } @alert_plugins;
}
else {
%alert_plugins = map { $_ => 1 } (1..scalar(@plugins));
}
# run each plugin and store its output in a report
$time_start = time;
my $i = 0;
foreach my $p( @plugins ) {
$i++;
my $plugin_timeout = shift(@alarm_times) || $default_timeout;
# run the plugin
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $plugin_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $plugin_timeout;
my $output = `$p`;
chomp $output;
if( $output !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - plugin $i error: $output\n";
print "Plugin $i: $p\n" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'UNKNOWN',$i,$output) if $tokenfile;
exit $status{UNKNOWN};
}
if( $output =~ m/CRITICAL/ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY CRITICAL - plugin $i failed: $output\n";
print "Plugin $i: $p" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'CRITICAL',$i,$output) if $tokenfile;
exit $status{CRITICAL};
}
if( $output =~ m/WARNING/ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY WARNING - plugin $i warning: $output\n";
print "Plugin $i: $p\n" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'WARNING',$i,$output) if $tokenfile;
exit $status{WARNING};
}
$report->{"plugin".$i} = $output;
alarm 0;
};
if( $@ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY CRITICAL - Could not run plugin $i: $@\n";
print "Plugin $i: $p\n" if $verbose;
exit $status{CRITICAL};
}
# if this wasn't the last plugin, wait before continuing
if( $i < scalar(@plugins) ) {
my $wait = shift(@wait_times) || $default_wait;
sleep $wait;
}
# compatibility with the "not using plugins" method... pretend to calculate the total round trip time (the delay) using data from the plugins ...
$report->{max} = 0;
$report->{delay} = 0;
}
# register the list of reports
foreach my $r ( 1..scalar(@plugins)) {
push @report_plugins, "plugin".$r;
}
# record tokens in a file if option is enabled
my $tmp_long_report = join(", ", map { "$_: $report->{$_}" } @report_plugins ) if $tokenfile;
record_tokens($tokenfile,\@tokens,$time_start,time,'OK',scalar(@plugins),$tmp_long_report) if $tokenfile;
}
else {
# not using plugins.
$time_start = time;
# send email via SMTP
my $id = $time_start; # XXX should include localhost name maybe or some random number in case the same mailbox is used for multiple delivery tests
my $smtp_plugin = "$libexec/check_smtp_send";
$smtp_plugin = "$libexec/check_smtp_send.pl" unless -e $smtp_plugin;
my $smtp_timeout = shift(@alarm_times) || $default_timeout;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $smtp_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $smtp_timeout;
my $smtp = `$smtp_plugin $smtp_options --header 'Subject: Nagios Message SMTP $smtp_server ID $id.' --body 'Nagios Email Delivery Plugin\n$body' $smtp_thresholds`;
if( $smtp !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - smtp unknown: $smtp\n";
exit $status{UNKNOWN};
}
if( $smtp =~ m/CRITICAL/ ) {
print "EMAIL DELIVERY CRITICAL - smtp failed: $smtp\n";
exit $status{CRITICAL};
}
chomp $smtp;
$report->{smtp} = $smtp;
alarm 0;
};
if( $@ ) {
print "EMAIL DELIVERY CRITICAL - Could not connect to SMTP server $smtp_server: $@\n";
exit $status{CRITICAL};
}
# wait before checking the delivery
$wait = shift(@wait_times) || $default_wait;
sleep $wait;
# check email via IMAP
my $imap_plugin = "$libexec/check_imap_receive";
$imap_plugin = "$libexec/check_imap_receive.pl" unless -e $imap_plugin;
my $imap_timeout = shift(@alarm_times) || $default_timeout;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $imap_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $imap_timeout;
my $imap = `$imap_plugin $imap_options -s SUBJECT -s 'Nagios Message SMTP $smtp_server ID' --capture-max 'Nagios Message SMTP $smtp_server ID (\\d+)' --nodelete-captured $imap_thresholds`;
if( $imap !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - imap unknown: $imap\n";
exit $status{UNKNOWN};
}
if( $imap =~ m/CRITICAL/ ) {
print "EMAIL DELIVERY CRITICAL - imap failed: $imap\n";
exit $status{CRITICAL};
}
if( $imap =~ m/ (\d+) max/ ) {
my $last_received = $1;
$report->{max} = $1;
my $delay = time - $last_received;
$report->{delay} = $delay;
}
chomp $imap;
$report->{imap} = $imap;
alarm 0;
};
if( $@ ) {
print "EMAIL DELIVERY CRITICAL - Could not connect to IMAP server $imap_server: $@\n";
exit $status{CRITICAL};
}
# register the list of reports
push @report_plugins, ("smtp","imap");
}
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
my @warning = ();
my @critical = ();
push @warning, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_warn );
push @critical, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_crit );
push @warning, "no emails found" if( !defined($report->{delay}) );
# print report and exit with known status
my $perf_data = "delay=".$report->{delay}."s;$delay_warn;$delay_crit;0 elapsed=".$report->{seconds}."s"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6
my $short_report = $report->text(qw/seconds delay/) . " | $perf_data";
my $long_report = join("", map { "$_: $report->{$_}\n" } @report_plugins );
if( scalar @critical ) {
my $alerts = join(", ", @critical);
print "EMAIL DELIVERY CRITICAL - $alerts; $short_report\n";
print $long_report if $verbose;
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $alerts = join(", ", @warning);
print "EMAIL DELIVERY WARNING - $alerts; $short_report\n";
print $long_report if $verbose;
exit $status{WARNING};
}
print "EMAIL DELIVERY OK - $short_report\n";
print $long_report if $verbose;
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# returns one random character from a set of characters
sub pick_random {
my @set = @_;
my $size = scalar @set;
my $string = $set[int(rand($size))];
return $string;
}
# appens tokens and times to a tab-separated value file
sub record_tokens {
my ($tokenfile,$tokens,$time_start,$time_end,$status,$plugin_num,$output) = @_;
if( $tokenfile ) {
my @tokens = @$tokens;
$time_end = "" unless defined $time_end;
$status = "" unless defined $status;
$plugin_num = "" unless defined $plugin_num;
$output = "" unless defined $output;
print "saving ".scalar(@tokens)." tokens into $tokenfile\n" if $verbose;
open(TOKENFILE,">>$tokenfile");
foreach(@tokens) {
print TOKENFILE "$_\t$time_start\t$time_end\t$status\t$plugin_num\t$output\n";
}
close(TOKENFILE);
}
}
# wraps argument in single-quotes and escapes any single-quotes in the argument
sub shellquote {
my $str = shift || "";
$str =~ s/\'/\'\\\'\'/g;
return "'$str'";
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package main;
1;
__END__
=pod
=head1 NAME
check_email_delivery - sends email and verifies delivery
=head1 SYNOPSIS
check_email_delivery -vV
check_email_delivery --usage
check_email_delivery --help
=head1 OPTIONS
=over
=item --warning <seconds>[,<smtp_seconds>,<imap_seconds>]
Exit with WARNING if the most recent email found is older than <seconds>. The
optional <smtp_seconds> and <imap_seconds> parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -w <seconds>[,<send>[,<recv>]]
When using the --plugin option, only one parameter is supported (-w <seconds>) and it will apply
to the entire process. You can specify a warning threshold specific to each plugin in the
plugin command line.
When using the --plugin option, no measuring of "most recent email" is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.
=item --critical <seconds>[,<smtp_seconds>,<imap_seconds>]
Exit with CRITICAL if the most recent email found is older than <seconds>. The
optional <smtp_seconds> and <imap_seconds> parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -c <seconds>[,<send>[,<recv>]]
When using the --plugin option, only one parameter is supported (-c <seconds>) and it will apply
to the entire process. You can specify a critical threshold specific to each plugin in the
plugin command line.
When using the --plugin option, no measuring of "most recent email" is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.
=item --timeout <seconds>
=item --timeout <smtp_seconds>,<imap_seconds>
=item --timeout <plugin1_seconds>,<plugin2_seconds>,...
Exit with CRITICAL if the plugins do not return a status within the specified number of seconds.
When only one parameter is used, it applies to each plugin. When multiple parameters are used
(separated by commas) they apply to plugins in the same order the plugins were specified on the
command line. When using --timeout but not the --plugin option, the first parameter is for
check_smtp_send and the second is for check_imap_receive.
=item --alert <pluginN>
Exit with WARNING or CRITICAL only if a warning or error (--warning, --critical, or --timeout)
occurs for specified plugins. If a warning or error occurs for non-specified plugins that run
BEFORE the specified plugins, the exit status will be UNKNOWN. If a warning of error occurs
for non-specified plugins that run AFTER the specified plugins, the exit status will not be
affected.
You would use this option if you are using check_email_delivery with the --plugin option and
the plugins you configure each use different servers, for example different SMTP and IMAP servers.
By default, if you do not use the --alert option, if anything goes wrong during the email delivery
check, a WARNING or CRITICAL alert will be issued. This means that if you define check_email_delivery
for the SMTP server only and the IMAP server fails, Nagios will alert you for the SMTP server which
would be misleading. If you define it for both the SMTP server and IMAP server and just one of them
fails, Nagios will alert you for both servers, which would still be misleading. If you have this
situation, you may want to use the --alert option. You define the check_email_delivery check for
both servers: for the SMTP server (first plugin) you use --alert 1, and for for the IMAP server
(second plugin) you use --alert 2. When check_email_delivery runs with --alert 1 and the SMTP
server fails, you will get the appropriate alert. If the IMAP server fails it will not affect the
status. When check_email_delivery runs with --alert 2 and the SMTP server fails, you will get the
UNKNOWN return code. If the IMAP server generates an alert you will get a WARNING or CRITICAL as
appropriate.
You can repeat this option to specify multiple plugins that should cause an alert.
Do this if you have multiple plugins on the command line but some of them involve the same server.
See also: --plugin.
Also known as: -A <pluginN>
=item --wait <seconds>[,<seconds>,...]
How long to wait between sending the message and checking that it was received. View default with
the -vV option.
When using the --plugin option, you can specify as many wait-between times as you have plugins
(minus the last plugin, because it makes no sense to wait after running the last one). For
example, if you use the --plugin option twice to specify an SMTP plugin and an IMAP plugin, and
you want to wait 5 seconds between sending and receiving, then you would specify --wait 5. A second
example, if you are using the --plugin option three times, then specifying -w 5 will wait 5 seconds
between the second and third plugins also. You can specify a different wait time
of 10 seconds between the second and third plugins, like this: -w 5,10.
=item --hostname <server>
Address or name of the SMTP and IMAP server. Examples: mail.server.com, localhost, 192.168.1.100.
Also known as: -H <server>
=item --smtp-server <server>
Address or name of the SMTP server. Examples: smtp.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.
=item --smtp-port <number>
Service port on the SMTP server. Default is 25.
=item --smtp-username <username>
=item --smtp-password <password>
Username and password to use when connecting to the SMTP server with the TLS option.
Use these options if the SMTP account has a different username/password than the
IMAP account you are testing. These options take precendence over the --username and
the --password options.
These are shell-escaped; special characters are ok.
=item --imap-server <server>
Address or name of the IMAP server. Examples: imap.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.
=item --imap-port <number>
Service port on the IMAP server. Default is 143. If you use SSL the default is 993.
=item --imap-username <username>
=item --imap-password <password>
Username and password to use when connecting to the IMAP server.
Use these options if the IMAP account has a different username/password than the
SMTP account you are testing. These options take precendence over the --username and
the --password options.
These are shell-escaped; special characters are ok.
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
Also used as the username and password for SMTP when the TLS option is enabled.
To specify a separate set of credentials for SMTP authentication, see the
options --smtp-username and --smtp-password.
=item --imap-check-interval <seconds>
How long to wait between polls of the imap-server for the specified mail. Default is 5 seconds.
=item --imap-retries <times>
How many times to poll the imap-server for the mail, before we give up. Default is 10.
=item --body <message>
Use this option to specify the body of the email message.
=item --header <header>
Use this option to set an arbitrary header in the message. You can use it multiple times.
=item --mailto recipient@your.net
You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):
$ check_email_delivery ... --mailto recipient@your.net,recipient2@your.net --mailfrom sender@your.net
This argument is shell-escaped; special characters or angle brackets around the address are ok.
=item --mailfrom sender@your.net
Use this option to set the "from" address in the email.
=item --imapssl
=item --noimapssl
Use this to enable or disable SSL for the IMAP plugin.
This argument is shell-escaped; special characters or angle brackets around the address are ok.
=item --smtptls
=item --nosmtptls
Use this to enable or disable TLS/AUTH for the SMTP plugin.
=item --libexec
Use this option to set the path of the Nagios libexec directory. The default is
/usr/local/nagios/libexec. This is where this plugin looks for the SMTP and IMAP
plugins that it depends on.
=item --plugin <command>
This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It frees the plugin from depending on specific external plugins and generalizes the
work done to determine that the email loop is operational. When using the --plugin
option, the following options are ignored: libexec, imapssl, smtptls, hostname,
username, password, smtp*, imap*, mailto, mailfrom, body, header, search.
Use this option multiple times to specify the complete trip. Typically, you would use
this twice to specify plugins for SMTP and IMAP, or SMTP and POP3.
The output will be success if all the plugins return success. Each plugin should be a
standard Nagios plugin.
A random token will be automatically generated and passed to each plugin specified on
the command line by substituting the string %TOKEN1%.
Example usage:
command_name check_email_delivery
command_line check_email_delivery
--plugin "$USER1$/check_smtp_send -H $ARG1$ --mailto recipient@your.net --mailfrom sender@your.net --header 'Subject: Nagios Test %TOKEN1%.'"
--plugin "$USER1$/check_imap_receive -H $ARG1$ -U $ARG1$ -P $ARG2$ -s SUBJECT -s 'Nagios Test %TOKEN1%.'"
This technique allows for a lot of flexibility in configuring the plugins that test
each part of your email delivery loop.
See also: --token.
Also known as: -p <command>
=item --token <format>
This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It can be used in conjunction with --plugin to control the tokens that are generated
and passed to the plugins, like %TOKEN1%.
Use this option multiple times to specify formats for different tokens. For example,
if you want %TOKEN1% to consist of only alphabetical characters but want %TOKEN2% to
consist of only digits, then you might use these options: --token aaaaaa --token nnnnn
Any tokens used in your plugin commands that have not been specified by --token <format>
will default to --token U-X-Y
Token formats:
a - alpha character (a-z)
n - numeric character (0-9)
c - alphanumeric character (a-z0-9)
h - hexadecimal character (0-9a-f)
U - unix time, seconds from epoch. eg 1193012441
X - a word from the pgp even list. eg aardvark
Y - a word from the pgp odd list. eg adroitness
Caution: It has been observed that some IMAP servers do not handle underscores well in the
search criteria. For best results, avoid using underscores in your tokens. Use hyphens or commas instead.
See also: --plugin.
Also known as: -T <format>
The PGP word list was obtained from http://en.wikipedia.org/wiki/PGP_word_list
=item --file <file>
Save (append) status information into the given tab-delimited file. Format used:
token start-time end-time status plugin-num output
Note: format may change in future versions and may become configurable.
This option available as of version 0.6.2.
Also known as: -F <file>
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Send a message with custom headers
$ check_email_delivery -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--username recipient --password secret
EMAIL DELIVERY OK - 1 seconds
=head2 Set warning and critical timeouts for receive plugin only:
$ check_email_delivery -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--username recipient --password secret -w ,,5 -c ,,15
EMAIL DELIVERY OK - 1 seconds
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 CHANGES
Wed Oct 29 13:08:00 PST 2005
+ version 0.1
Wed Nov 9 17:16:09 PST 2005
+ updated arguments to check_smtp_send and check_imap_receive
+ added eval/alarm block to implement -c option
+ added wait option to adjust sleep time between smtp and imap calls
+ added delay-warn and delay-crit options to adjust email delivery warning thresholds
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson <johann (at) axis.com>)
+ version 0.2.1
+ corrected bug in getoptions ($imap_server would never ever be set from command-line...)
+ will not make $smtp_server and $imap_server == $host if they're defined on commandline
+ added support for multiple polls of imap-server, with specified intervals
+ changed default behaviour in check_imap_server (searches for the specific id in subject and deletes mails found)
+ increased default delay_warn from 65 seconds to 95 seconds
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton <geoff.crompton@strategicdata.com.au>)
+ fixed a bug in getoptions
+ version 0.2.2
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ version 0.2.3
Fri Apr 27 20:32:53 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ changed connection error to display timeout only if timeout was the error
+ default IMAP plugin is libexec/check_imap_receive (also checking for same but with .pl extension)
+ default SMTP plugin is libexec/check_smtp_send (also checking for same but with .pl extension)
+ removed default values for SMTP port and IMAP port to allow those plugins to set the defaults; so current behavior stays the same and will continue to make sense with SSL
+ version 0.3
Thu Oct 11 10:00:00 EET 2007 (by Timo Virtaneva <timo (at) virtaneva dot com>
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.3.1
Sun Oct 21 11:01:03 PDT 2007
+ added support for TLS options to the SMTP plugin
+ version 0.4
Sun Oct 21 16:17:14 PDT 2007
+ added support for arbitrary plugins to send and receive mail (or anthing else!). see the --plugin option.
+ version 0.5
Tue Dec 4 07:36:20 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ shortcut option for --token is now -T to avoid clash with standard shortcut -t for --timeout
+ fixed some minor pod formatting issues for perldoc
+ version 0.5.1
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.5.2
Thu Jan 17 20:27:36 PST 2008 (by Timo Virtaneva <timo (at) virtaneva dot com> on Thu Oct 11 10:00:00 EET 2007)
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.5.3
Mon Jan 28 22:11:02 PST 2008
+ fixed a bug, smtp-password and imap-password are now string parameters
+ added --alert option to allow selection of which plugin(s) should cause a WARNING or CRITICAL alert
+ version 0.6
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.6.1
Mon May 26 10:39:19 PDT 2008
+ added --file option to allow plugin to record status information into a tab-delimited file
+ changed default token from U_X_Y to U-X-Y
+ version 0.6.2
Wed Jan 14 08:29:35 PST 2009
+ fixed a bug that the --header parameter was not being passed to the smtp plugin.
+ version 0.6.3
Mon Jun 8 15:43:48 PDT 2009
+ added performance data for use with PNP4Nagios! (thanks to Ben Ritcey for the patch)
+ version 0.6.4
Wed Sep 16 07:10:10 PDT 2009
+ added elapsed time in seconds to performance data
+ version 0.6.5
Fri Oct 8 19:48:44 PDT 2010
+ fixed uniform IMAP and SMTP username and password bug (thanks to Micle Moerenhout for pointing it out)
+ version 0.6.6
Mon Jan 3 08:24:23 PST 2011
+ added shell escaping for smtp-username, smtp-password, mailto, mailfrom, imap-username, and imap-password arguments
+ version 0.7.0
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1
Sun Jun 12 17:17:06 AST 2011
+ added --imap-mailbox option to pass through to check_imap_receive --mailbox option
+ added --ssl option to conveniently enable both --smtp-tls and --imap-ssl
+ version 0.7.2
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,498 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.7.1';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $host = "";
my $smtp_server = "";
my $smtp_port = "";
my $imap_server = "";
my $smtp_username = "";
my $smtp_password = "";
my $smtp_tls = "";
my $imap_port = "";
my $imap_username = "";
my $imap_password = "";
my $imap_mailbox = "";
my $username = "";
my $password = "";
my $ssl = "";
my $imap_ssl = "";
my $mailto = "";
my $mailfrom = "";
my @header = ();
my $body = "";
my $warnstr = "";
my $critstr = "";
my $waitstr = "";
my $delay_warn = 95;
my $delay_crit = 300;
my $smtp_warn = 15;
my $smtp_crit = 30;
my $imap_warn = 15;
my $imap_crit = 30;
my $timeout = "";
my @alert_plugins = ();
my $imap_interval = 5;
my $imap_retries = 5;
my @plugins = ();
my @token_formats = ();
my $tokenfile = "";
my $default_crit = 30;
my $default_warn = 15;
my $default_wait = 5;
my $default_timeout = 60;
my $time_hires = "";
my $libexec = "/usr/local/nagios/libexec";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=s"=>\$warnstr,"c|critical=s"=>\$critstr, "t|timeout=s"=>\$timeout,
"libexec=s"=>\$libexec,
# plugin settings
"p|plugin=s"=>\@plugins, "T|token=s"=>\@token_formats,
"A|alert=i"=>\@alert_plugins,
"F|file=s"=>\$tokenfile,
# common settings
"H|hostname=s"=>\$host,
"U|username=s"=>\$username,"P|password=s"=>\$password,
"ssl!"=>\$ssl,
# smtp settings
"smtp-server=s"=>\$smtp_server,"smtp-port=i"=>\$smtp_port,
"mailto=s"=>\$mailto, "mailfrom=s",\$mailfrom,
"header=s"=>\@header, "body=s"=>\$body,
# smtp-tls settings
"smtptls!"=>\$smtp_tls,
"smtp-username=s"=>\$smtp_username,"smtp-password=s"=>\$smtp_password,
# delay settings
"wait=s"=>\$waitstr,
# imap settings
"imap-server=s"=>\$imap_server,"imap-port=i"=>\$imap_port,
"imap-username=s"=>\$imap_username,"imap-password=s"=>\$imap_password,
"imap-mailbox=s"=>\$imap_mailbox,
"imap-check-interval=i"=>\$imap_interval,"imap-retries=i"=>\$imap_retries,
"imapssl!"=>\$imap_ssl,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Warning threshold: $delay_warn seconds\n";
print "Critical threshold: $delay_crit seconds\n";
print "Default wait: $default_wait seconds\n";
print "Default timeout: $default_timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $host ) {
$smtp_server = $host if $smtp_server eq "";
$imap_server = $host if $imap_server eq "";
}
if( $username ) {
$smtp_username = $username if $smtp_username eq "";
$imap_username = $username if $imap_username eq "";
}
if( $password ) {
$smtp_password = $password if $smtp_password eq "";
$imap_password = $password if $imap_password eq "";
}
if( $ssl ) {
$imap_ssl = $ssl if $imap_ssl eq "";
$smtp_tls = $ssl if $smtp_tls eq "";
}
if( $help_usage
||
(
scalar(@plugins) == 0
&&
(
$smtp_server eq "" || $mailto eq "" || $mailfrom eq ""
|| $imap_server eq "" || $username eq "" || $password eq ""
)
)
) {
print "Usage 1: $0 -H host \n\t".
"--mailto recipient\@your.net --mailfrom sender\@your.net --body 'message' \n\t".
"--username username --password password \n\t".
"[-w <seconds>] [-c <seconds>]\n\t" .
"[--imap-check-interval <seconds> ] [--imap-retries <times> ]\n";
print "Usage 2: $0 \n\t".
"-p 'first plugin command with %TOKEN1% embedded' \n\t".
"-p 'second plugin command with %TOKEN1% embedded' \n\t".
"[-w <seconds1>,<seconds2>] [-c <seconds1>,<seconds2>] \n";
exit $status{UNKNOWN};
}
# determine thresholds
my @warning_times = split(",", $warnstr);
my @critical_times = split(",", $critstr);
my @alarm_times = split(",", $timeout);
my @wait_times = split(",", $waitstr);
my ($dw,$sw,$rw) = split(",", $warnstr);
my ($dc,$sc,$rc) = split(",", $critstr);
my ($wait) = split(",", $waitstr);
$delay_warn = $dw if defined $dw and $dw ne "";
$smtp_warn = $sw if defined $sw and $sw ne "";
$imap_warn = $rw if defined $rw and $rw ne "";
$delay_crit = $dc if defined $dc and $dc ne "";
$smtp_crit = $sc if defined $sc and $sc ne "";
$imap_crit = $rc if defined $rc and $rc ne "";
my $smtp_thresholds = "";
$smtp_thresholds .= "-w $smtp_warn " if defined $smtp_warn and $smtp_warn ne "";
$smtp_thresholds .= "-c $smtp_crit " if defined $smtp_crit and $smtp_crit ne "";
my $imap_thresholds = "";
$imap_thresholds .= "-w $imap_warn " if defined $imap_warn and $imap_warn ne "";
$imap_thresholds .= "-c $imap_crit " if defined $imap_crit and $imap_crit ne "";
$imap_thresholds .= "--imap-check-interval $imap_interval " if defined $imap_interval and $imap_interval ne "";
$imap_thresholds .= "--imap-retries $imap_retries " if defined $imap_retries and $imap_retries ne "";
if( scalar(@alarm_times) == 1 ) {
$default_timeout = shift(@alarm_times);
}
# determine which other options to include
my $smtp_options = "";
$smtp_options .= "-H $smtp_server " if defined $smtp_server and $smtp_server ne "";
$smtp_options .= "-p $smtp_port " if defined $smtp_port and $smtp_port ne "";
$smtp_options .= "--tls " if defined $smtp_tls and $smtp_tls;
$smtp_options .= "-U ".shellquote($smtp_username)." " if defined $smtp_username and $smtp_username ne "";
$smtp_options .= "-P ".shellquote($smtp_password)." " if defined $smtp_password and $smtp_password ne "";
$smtp_options .= "--mailto ".shellquote($mailto)." " if defined $mailto and $mailto ne "";
$smtp_options .= "--mailfrom ".shellquote($mailfrom)." " if defined $mailfrom and $mailfrom ne "";
foreach my $h( @header ) {
$smtp_options .= "--header ".shellquote($h)." ";
}
my $imap_options = "";
$imap_options .= "-H $imap_server " if defined $imap_server and $imap_server ne "";
$imap_options .= "-p $imap_port " if defined $imap_port and $imap_port ne "";
$imap_options .= "-U ".shellquote($imap_username)." " if defined $imap_username and $imap_username ne "";
$imap_options .= "-P ".shellquote($imap_password)." " if defined $imap_password and $imap_password ne "";
$imap_options .= "--mailbox ".shellquote($imap_mailbox)." " if defined $imap_mailbox and $imap_mailbox ne "";
$imap_options .= "--ssl " if defined $imap_ssl and $imap_ssl;
# create the report object
my $report = new PluginReport;
my @report_plugins = (); # populated later with either (smtp,imap) or (plugin1,plugin2,...)
my $time_start; # initialized later with time the work actually starts
# create token formats for use with the plugins
my @alpha = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z/;
my @numeric = qw/0 1 2 3 4 5 6 7 8 9/;
my @hex = qw/0 1 2 3 4 5 6 7 8 9 a b c d e f/;
my @pgp_even = qw/aardvark absurd accrue acme adrift adult afflict ahead aimless Algol allow alone ammo ancient apple artist assume Athens atlas Aztec baboon backfield backward banjo beaming bedlamp beehive beeswax befriend Belfast berserk billiard bison blackjack blockade blowtorch bluebird bombast bookshelf brackish breadline breakup brickyard briefcase Burbank button buzzard cement chairlift chatter checkup chisel choking chopper Christmas clamshell classic classroom cleanup clockwork cobra commence concert cowbell crackdown cranky crowfoot crucial crumpled crusade cubic dashboard deadbolt deckhand dogsled dragnet drainage dreadful drifter dropper drumbeat drunken Dupont dwelling eating edict egghead eightball endorse endow enlist erase escape exceed eyeglass eyetooth facial fallout flagpole flatfoot flytrap fracture framework freedom frighten gazelle Geiger glitter glucose goggles goldfish gremlin guidance hamlet highchair hockey indoors indulge inverse involve island jawbone keyboard kickoff kiwi klaxon locale lockup merit minnow miser Mohawk mural music necklace Neptune newborn nightbird Oakland obtuse offload optic orca payday peachy pheasant physique playhouse Pluto preclude prefer preshrunk printer prowler pupil puppy python quadrant quiver quota ragtime ratchet rebirth reform regain reindeer rematch repay retouch revenge reward rhythm ribcage ringbolt robust rocker ruffled sailboat sawdust scallion scenic scorecard Scotland seabird select sentence shadow shamrock showgirl skullcap skydive slingshot slowdown snapline snapshot snowcap snowslide solo southward soybean spaniel spearhead spellbind spheroid spigot spindle spyglass stagehand stagnate stairway standard stapler steamship sterling stockman stopwatch stormy sugar surmount suspense sweatband swelter tactics talon tapeworm tempest tiger tissue tonic topmost tracker transit trauma treadmill Trojan trouble tumor tunnel tycoon uncut unearth unwind uproot upset upshot vapor village virus Vulcan waffle wallet watchword wayside willow woodlark Zulu/;
my @pgp_odd = qw/adroitness adviser aftermath aggregate alkali almighty amulet amusement antenna applicant Apollo armistice article asteroid Atlantic atmosphere autopsy Babylon backwater barbecue belowground bifocals bodyguard bookseller borderline bottomless Bradbury bravado Brazilian breakaway Burlington businessman butterfat Camelot candidate cannonball Capricorn caravan caretaker celebrate cellulose certify chambermaid Cherokee Chicago clergyman coherence combustion commando company component concurrent confidence conformist congregate consensus consulting corporate corrosion councilman crossover crucifix cumbersome customer Dakota decadence December decimal designing detector detergent determine dictator dinosaur direction disable disbelief disruptive distortion document embezzle enchanting enrollment enterprise equation equipment escapade Eskimo everyday examine existence exodus fascinate filament finicky forever fortitude frequency gadgetry Galveston getaway glossary gossamer graduate gravity guitarist hamburger Hamilton handiwork hazardous headwaters hemisphere hesitate hideaway holiness hurricane hydraulic impartial impetus inception indigo inertia infancy inferno informant insincere insurgent integrate intention inventive Istanbul Jamaica Jupiter leprosy letterhead liberty maritime matchmaker maverick Medusa megaton microscope microwave midsummer millionaire miracle misnomer molasses molecule Montana monument mosquito narrative nebula newsletter Norwegian October Ohio onlooker opulent Orlando outfielder Pacific pandemic Pandora paperweight paragon paragraph paramount passenger pedigree Pegasus penetrate perceptive performance pharmacy phonetic photograph pioneer pocketful politeness positive potato processor provincial proximate puberty publisher pyramid quantity racketeer rebellion recipe recover repellent replica reproduce resistor responsive retraction retrieval retrospect revenue revival revolver sandalwood sardonic Saturday savagery scavenger sensation sociable souvenir specialist speculate stethoscope stupendous supportive surrender suspicious sympathy tambourine telephone therapist tobacco tolerance tomorrow torpedo tradition travesty trombonist truncated typewriter ultimate undaunted underfoot unicorn unify universe unravel upcoming vacancy vagabond vertigo Virginia visitor vocalist voyager warranty Waterloo whimsical Wichita Wilmington Wyoming yesteryear Yucatan/;
my %formats = (
'a' => sub { pick_random(@alpha) },
'n' => sub { pick_random(@numeric) },
'c' => sub { pick_random(@alpha,@numeric) },
'h' => sub { pick_random(@hex) },
'U' => sub { time },
'X' => sub { pick_random(@pgp_even) },
'Y' => sub { pick_random(@pgp_odd) },
);
if( scalar(@plugins) ) {
# scan the plugin commands for use of tokens to count how many we need
my $token_count = 0;
foreach my $p (@plugins) {
my @matches = sort ($p =~ m/%TOKEN(\d+)%/g);
my $max = pop @matches;
$token_count = $max if defined($max) && $max > $token_count;
}
# create the tokens
my @tokens = ();
foreach my $t (1..$token_count) {
my $format = shift @token_formats;
$format = "U-X-Y" unless $format;
my @format_characters = split(//, $format);
my $token = "";
foreach my $c (@format_characters) {
if( defined $formats{$c} ) {
$token .= &{$formats{$c}};
}
else {
$token .= $c;
}
}
push @tokens, $token;
}
# substitute the tokens into each plugin command
foreach my $p (@plugins) {
foreach my $t (1..$token_count) {
my $token = $tokens[$t-1];
$p =~ s/%TOKEN$t%/$token/g;
}
}
# mark plugins that are allowed to generate alerts. default behavior is to alert for all plugins.
my %alert_plugins = ();
if( scalar(@alert_plugins) > 0 ) {
%alert_plugins = map { $_ => 1 } @alert_plugins;
}
else {
%alert_plugins = map { $_ => 1 } (1..scalar(@plugins));
}
# run each plugin and store its output in a report
$time_start = time;
my $i = 0;
foreach my $p( @plugins ) {
$i++;
my $plugin_timeout = shift(@alarm_times) || $default_timeout;
# run the plugin
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $plugin_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $plugin_timeout;
my $output = `$p`;
chomp $output;
if( $output !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - plugin $i error: $output\n";
print "Plugin $i: $p\n" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'UNKNOWN',$i,$output) if $tokenfile;
exit $status{UNKNOWN};
}
if( $output =~ m/CRITICAL/ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY CRITICAL - plugin $i failed: $output\n";
print "Plugin $i: $p" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'CRITICAL',$i,$output) if $tokenfile;
exit $status{CRITICAL};
}
if( $output =~ m/WARNING/ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY WARNING - plugin $i warning: $output\n";
print "Plugin $i: $p\n" if $verbose;
# record tokens in a file if option is enabled
record_tokens($tokenfile,\@tokens,$time_start,undef,'WARNING',$i,$output) if $tokenfile;
exit $status{WARNING};
}
$report->{"plugin".$i} = $output;
alarm 0;
};
if( $@ && $alert_plugins{$i} ) {
print "EMAIL DELIVERY CRITICAL - Could not run plugin $i: $@\n";
print "Plugin $i: $p\n" if $verbose;
exit $status{CRITICAL};
}
# if this wasn't the last plugin, wait before continuing
if( $i < scalar(@plugins) ) {
my $wait = shift(@wait_times) || $default_wait;
sleep $wait;
}
# compatibility with the "not using plugins" method... pretend to calculate the total round trip time (the delay) using data from the plugins ...
$report->{max} = 0;
$report->{delay} = 0;
}
# register the list of reports
foreach my $r ( 1..scalar(@plugins)) {
push @report_plugins, "plugin".$r;
}
# record tokens in a file if option is enabled
my $tmp_long_report = join(", ", map { "$_: $report->{$_}" } @report_plugins ) if $tokenfile;
record_tokens($tokenfile,\@tokens,$time_start,time,'OK',scalar(@plugins),$tmp_long_report) if $tokenfile;
}
else {
# not using plugins.
$time_start = time;
# send email via SMTP
my $id = $time_start; # XXX should include localhost name maybe or some random number in case the same mailbox is used for multiple delivery tests
my $smtp_plugin = "$libexec/check_smtp_send";
$smtp_plugin = "$libexec/check_smtp_send.pl" unless -e $smtp_plugin;
my $smtp_timeout = shift(@alarm_times) || $default_timeout;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $smtp_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $smtp_timeout;
my $smtp = `$smtp_plugin $smtp_options --header 'Subject: Nagios Message SMTP $smtp_server ID $id.' --body 'Nagios Email Delivery Plugin\n$body' $smtp_thresholds`;
if( $smtp !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - smtp unknown: $smtp\n";
exit $status{UNKNOWN};
}
if( $smtp =~ m/CRITICAL/ ) {
print "EMAIL DELIVERY CRITICAL - smtp failed: $smtp\n";
exit $status{CRITICAL};
}
chomp $smtp;
$report->{smtp} = $smtp;
alarm 0;
};
if( $@ ) {
print "EMAIL DELIVERY CRITICAL - Could not connect to SMTP server $smtp_server: $@\n";
exit $status{CRITICAL};
}
# wait before checking the delivery
$wait = shift(@wait_times) || $default_wait;
sleep $wait;
# check email via IMAP
my $imap_plugin = "$libexec/check_imap_receive";
$imap_plugin = "$libexec/check_imap_receive.pl" unless -e $imap_plugin;
my $imap_timeout = shift(@alarm_times) || $default_timeout;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $imap_timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $imap_timeout;
my $imap = `$imap_plugin $imap_options -s SUBJECT -s 'Nagios Message SMTP $smtp_server ID' --capture-max 'Nagios Message SMTP $smtp_server ID (\\d+)' --nodelete-captured $imap_thresholds`;
if( $imap !~ m/OK|WARNING|CRITICAL/ ) {
print "EMAIL DELIVERY UNKNOWN - imap unknown: $imap\n";
exit $status{UNKNOWN};
}
if( $imap =~ m/CRITICAL/ ) {
print "EMAIL DELIVERY CRITICAL - imap failed: $imap\n";
exit $status{CRITICAL};
}
if( $imap =~ m/ (\d+) max/ ) {
my $last_received = $1;
$report->{max} = $1;
my $delay = time - $last_received;
$report->{delay} = $delay;
}
chomp $imap;
$report->{imap} = $imap;
alarm 0;
};
if( $@ ) {
print "EMAIL DELIVERY CRITICAL - Could not connect to IMAP server $imap_server: $@\n";
exit $status{CRITICAL};
}
# register the list of reports
push @report_plugins, ("smtp","imap");
}
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
my @warning = ();
my @critical = ();
push @warning, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_warn );
push @critical, "most recent received $report->{delay} seconds ago" if( defined($report->{delay}) && $report->{delay} > $delay_crit );
push @warning, "no emails found" if( !defined($report->{delay}) );
# print report and exit with known status
my $perf_data = "delay=".$report->{delay}."s;$delay_warn;$delay_crit;0 elapsed=".$report->{seconds}."s"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6
my $short_report = $report->text(qw/seconds delay/) . " | $perf_data";
my $long_report = join("", map { "$_: $report->{$_}\n" } @report_plugins );
if( scalar @critical ) {
my $alerts = join(", ", @critical);
print "EMAIL DELIVERY CRITICAL - $alerts; $short_report\n";
print $long_report if $verbose;
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $alerts = join(", ", @warning);
print "EMAIL DELIVERY WARNING - $alerts; $short_report\n";
print $long_report if $verbose;
exit $status{WARNING};
}
print "EMAIL DELIVERY OK - $short_report\n";
print $long_report if $verbose;
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# returns one random character from a set of characters
sub pick_random {
my @set = @_;
my $size = scalar @set;
my $string = $set[int(rand($size))];
return $string;
}
# appens tokens and times to a tab-separated value file
sub record_tokens {
my ($tokenfile,$tokens,$time_start,$time_end,$status,$plugin_num,$output) = @_;
if( $tokenfile ) {
my @tokens = @$tokens;
$time_end = "" unless defined $time_end;
$status = "" unless defined $status;
$plugin_num = "" unless defined $plugin_num;
$output = "" unless defined $output;
print "saving ".scalar(@tokens)." tokens into $tokenfile\n" if $verbose;
open(TOKENFILE,">>$tokenfile");
foreach(@tokens) {
print TOKENFILE "$_\t$time_start\t$time_end\t$status\t$plugin_num\t$output\n";
}
close(TOKENFILE);
}
}
# wraps argument in single-quotes and escapes any single-quotes in the argument
sub shellquote {
my $str = shift || "";
$str =~ s/\'/\'\\\'\'/g;
return "'$str'";
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package main;
1;

View File

@ -0,0 +1,431 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.2';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
#### IDEA AND INITIAL IMPLEMENTATION BASED ON CHECK_IMAP_RECEIVE WAS CONTRIBUTED BY JOHAN ROMME from THE NETHERLANDS 14 Oct 2011
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Mail::IMAPClient/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $username = "";
my $password = "";
my $mailbox = "INBOX";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $peek = "";
my $ssl = 0;
my $tls = 0;
my $time_hires = "";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
"U|username=s"=>\$username,"P|password=s"=>\$password, "m|mailbox=s"=>\$mailbox,
"ssl!"=>\$ssl, "tls!"=>\$tls,
# search settings
"peek!"=>\$peek,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
my @required_module = ();
push @required_module, 'IO::Socket::SSL' if $ssl || $tls;
exit $status{UNKNOWN} unless load_modules(@required_module);
if( $help_usage
||
( $imap_server eq "" || $username eq "" || $password eq "" )
) {
print "Usage: $0 -H host [-p port] -U username -P password [--imap-retries <tries>]\n";
exit $status{UNKNOWN};
}
# initialize
my $report = new PluginReport;
my $time_start = time;
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
if( $ssl || $tls ) {
$imap_port = $default_imap_ssl_port unless $imap_port;
my $socket = IO::Socket::SSL->new("$imap_server:$imap_port");
die IO::Socket::SSL::errstr() unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
$imap->User($username);
$imap->Password($password);
$imap->login() or die "$@";
}
else {
$imap_port = $default_imap_port unless $imap_port;
$imap = Mail::IMAPClient->new(Debug => 0 );
$imap->Server("$imap_server:$imap_port");
$imap->User($username);
$imap->Password($password);
$imap->connect() or die "$@";
}
$imap->Peek(1) if $peek;
$imap->Ignoresizeerrors(1);
alarm 0;
};
if( $@ ) {
chomp $@;
print "IMAP QUOTA CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "IMAP QUOTA CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
my $time_connected = time;
my $quotaUsed;
my $quotaLimit;
my $quotaPercentage;
my $quotaPercentageWarning = 80;
my $quotaPercentageCritical = 90;
my $quotaMessage;
# look for the quota limits
my $tries = 0;
my @msgs;
eval {
my $k;
my @l = $imap->getquotaroot();
foreach $k (@l) {
print "$k\n" if $verbose > 2;
if ($k =~ /STORAGE +(\d+) +(\d+)/) {
$quotaUsed = $1;
$quotaLimit = $2;
}
}
if (!length($quotaUsed) && !length($quotaLimit)) {
print "no answer from imap host\n" if $verbose > 2;
} elsif (!length($quotaUsed) || !length($quotaLimit) {
print "incorrect answer from imap host\n";
$imap->close();
exit $status{UNKNOWN};
} else {
$quotaPercentage = sprintf("%.1f", (100 * $quotaUsed) / $quotaLimit);
$quotaMessage = "$quotaUsed $quotaLimit - $quotaPercentage%";
}
};
if( $@ ) {
chomp $@;
print "IMAP QUOTA CRITICAL - Could not check quota at $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
# print report and exit with known status
if($quotaPercentage >= $quotaPercentageCritical) {
print "IMAP QUOTA CRITICAL - $quotaMessage\n";
exit $status{CRITICAL};
}
if($quotaPercentage >= $quotaPercentageWarning) {
print "IMAP QUOTA WARNING - $quotaMessage\n";
exit $status{WARNING};
}
print "IMAP QUOTA OK - $quotaMessage\n";
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package main;
1;
__END__
=pod
=head1 NAME
check_imap_quota - connects to an IMAP account and checks the quota
=head1 SYNOPSIS
check_imap_quota -vV
check_imap_quota -?
check_imap_quota --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the IMAP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical <messages>
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
=item --mailbox <mailbox>
Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m <mailbox>
=item --ssl
=item --nossl
Enable SSL protocol. Requires IO::Socket::SSL.
Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.
Use the nossl option to turn off the ssl option.
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Report how many emails are in the mailbox
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete
IMAP RECEIVE OK - 1 seconds, 7 found
=head2 Report the email with the highest value
Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: <auto-000000992528@server.net>
Homeruns 5
And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s "Results of Autoscript" --capture-max "Homeruns (\d+)" --nodelete-captured
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted
=head2 Troubleshoot your search parameters
Add the --nodelete and --imap-retries=1 parameters to your command line.
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 SEE ALSO
http://nagios.org/
http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod
http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod
=head1 CHANGES
Fri Nov 11 04:53:09 AST 2011
+ version 0.1 created with quota code contributed by Johan Romme
Tue Dec 20 17:38:04 PST 2011
+ fixed bug where a quota of 0 was reported as an incorrect response from the server, thanks to Eike Arndt
+ version 0.2
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,235 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.2';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
#### IDEA AND INITIAL IMPLEMENTATION BASED ON CHECK_IMAP_RECEIVE WAS CONTRIBUTED BY JOHAN ROMME from THE NETHERLANDS 14 Oct 2011
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Mail::IMAPClient/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $username = "";
my $password = "";
my $mailbox = "INBOX";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $peek = "";
my $ssl = 0;
my $tls = 0;
my $time_hires = "";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
"U|username=s"=>\$username,"P|password=s"=>\$password, "m|mailbox=s"=>\$mailbox,
"ssl!"=>\$ssl, "tls!"=>\$tls,
# search settings
"peek!"=>\$peek,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
my @required_module = ();
push @required_module, 'IO::Socket::SSL' if $ssl || $tls;
exit $status{UNKNOWN} unless load_modules(@required_module);
if( $help_usage
||
( $imap_server eq "" || $username eq "" || $password eq "" )
) {
print "Usage: $0 -H host [-p port] -U username -P password [--imap-retries <tries>]\n";
exit $status{UNKNOWN};
}
# initialize
my $report = new PluginReport;
my $time_start = time;
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
if( $ssl || $tls ) {
$imap_port = $default_imap_ssl_port unless $imap_port;
my $socket = IO::Socket::SSL->new("$imap_server:$imap_port");
die IO::Socket::SSL::errstr() unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
$imap->User($username);
$imap->Password($password);
$imap->login() or die "$@";
}
else {
$imap_port = $default_imap_port unless $imap_port;
$imap = Mail::IMAPClient->new(Debug => 0 );
$imap->Server("$imap_server:$imap_port");
$imap->User($username);
$imap->Password($password);
$imap->connect() or die "$@";
}
$imap->Peek(1) if $peek;
$imap->Ignoresizeerrors(1);
alarm 0;
};
if( $@ ) {
chomp $@;
print "IMAP QUOTA CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "IMAP QUOTA CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
my $time_connected = time;
my $quotaUsed;
my $quotaLimit;
my $quotaPercentage;
my $quotaPercentageWarning = 80;
my $quotaPercentageCritical = 90;
my $quotaMessage;
# look for the quota limits
my $tries = 0;
my @msgs;
eval {
my $k;
my @l = $imap->getquotaroot();
foreach $k (@l) {
print "$k\n" if $verbose > 2;
if ($k =~ /STORAGE +(\d+) +(\d+)/) {
$quotaUsed = $1;
$quotaLimit = $2;
}
}
if (!length($quotaUsed) && !length($quotaLimit)) {
print "no answer from imap host\n" if $verbose > 2;
} elsif (!length($quotaUsed) || !length($quotaLimit) {
print "incorrect answer from imap host\n";
$imap->close();
exit $status{UNKNOWN};
} else {
$quotaPercentage = sprintf("%.1f", (100 * $quotaUsed) / $quotaLimit);
$quotaMessage = "$quotaUsed $quotaLimit - $quotaPercentage%";
}
};
if( $@ ) {
chomp $@;
print "IMAP QUOTA CRITICAL - Could not check quota at $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
# print report and exit with known status
if($quotaPercentage >= $quotaPercentageCritical) {
print "IMAP QUOTA CRITICAL - $quotaMessage\n";
exit $status{CRITICAL};
}
if($quotaPercentage >= $quotaPercentageWarning) {
print "IMAP QUOTA WARNING - $quotaMessage\n";
exit $status{WARNING};
}
print "IMAP QUOTA OK - $quotaMessage\n";
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package main;
1;

View File

@ -0,0 +1,999 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.7.5';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Mail::IMAPClient/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $username = "";
my $password = "";
my $mailbox = "INBOX";
my @search = ();
my $search_critical_min = 1;
my $search_critical_max = -1; # -1 means disabled for this option
my $search_warning_min = 1;
my $search_warning_max = -1; # -1 means disabled for this option
my $capture_max = "";
my $capture_min = "";
my $delete = 1;
my $no_delete_captured = "";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $interval = 5;
my $max_retries = 10;
my $download = "";
my $download_max = "";
my $peek = "";
my $template = "";
my $ssl = 0;
my $ssl_ca_file = "";
my $tls = 0;
my $time_hires = "";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
"U|username=s"=>\$username,"P|password=s"=>\$password, "m|mailbox=s"=>\$mailbox,
"imap-check-interval=i"=>\$interval,"imap-retries=i"=>\$max_retries,
"ssl!"=>\$ssl, "ssl-ca-file=s"=>\$ssl_ca_file, "tls!"=>\$tls,
# search settings
"s|search=s"=>\@search,
"search-critical-min=i"=>\$search_critical_min, "search-critical-max=i"=>\$search_critical_max,
"search-warning-min=i"=>\$search_warning_min, "search-warning-max=i"=>\$search_warning_max,
"capture-max=s"=>\$capture_max, "capture-min=s"=>\$capture_min,
"delete!"=>\$delete, "nodelete-captured"=>\$no_delete_captured,
"download!"=>\$download, "download_max=i"=>\$download_max, "download-max=i"=>\$download_max,
"peek!"=>\$peek,
"template!"=>\$template,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
my @required_module = ();
push @required_module, 'IO::Socket::SSL' if $ssl || $tls;
push @required_module, 'Email::Simple' if $download;
push @required_module, ('Text::Template','Date::Manip') if $template;
exit $status{UNKNOWN} unless load_modules(@required_module);
if( $help_usage
||
( $imap_server eq "" || $username eq "" || $password eq "" || scalar(@search)==0 )
) {
print "Usage: $0 -H host [-p port] -U username -P password -s HEADER -s X-Nagios -s 'ID: 1234.' [-w <seconds>] [-c <seconds>] [--imap-check-interval <seconds>] [--imap-retries <tries>]\n";
exit $status{UNKNOWN};
}
# before attempting to connect to the server, check if any of the search parameters
# use substitution functions and make sure we can parse them first. if we can't we
# need to abort since the search will be meaningless.
if( $template ) {
foreach my $token (@search) {
my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$token,PACKAGE=>'ImapSearchTemplate');
$token = $t->fill_in(PREPEND=>q{package ImapSearchTemplate;});
#print "token: $token\n";
}
}
# initialize
my $report = new PluginReport;
my $time_start = time;
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
if( $ssl || $tls ) {
$imap_port = $default_imap_ssl_port unless $imap_port;
my %ssl_args = ();
if( length($ssl_ca_file) > 0 ) {
$ssl_args{SSL_verify_mode} = 1;
$ssl_args{SSL_ca_file} = $ssl_ca_file;
$ssl_args{SSL_verifycn_scheme} = 'imap';
$ssl_args{SSL_verifycn_name} = $imap_server;
}
my $socket = IO::Socket::SSL->new(PeerAddr=>"$imap_server:$imap_port", %ssl_args);
die IO::Socket::SSL::errstr() . " (if you get this only when using both --ssl and --ssl-ca-file, but not when using just --ssl, the server SSL certificate failed validation)" unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
$imap->User($username);
$imap->Password($password);
$imap->login() or die "Cannot login: $@";
}
else {
$imap_port = $default_imap_port unless $imap_port;
$imap = Mail::IMAPClient->new(Debug => 0 );
$imap->Server("$imap_server:$imap_port");
$imap->User($username);
$imap->Password($password);
$imap->connect() or die "$@";
}
$imap->Peek(1) if $peek;
$imap->Ignoresizeerrors(1);
alarm 0;
};
if( $@ ) {
chomp $@;
print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
my $time_connected = time;
# select a mailbox
print "selecting mailbox $mailbox\n" if $verbose > 2;
unless( $imap->select($mailbox) ) {
print "IMAP RECEIVE CRITICAL - Could not select $mailbox: $@ $!\n";
if( $verbose > 2 ) {
print "Mailbox list:\n" . join("\n", $imap->folders) . "\n";
print "Mailbox separator: " . $imap->separator . "\n";
##print "Special mailboxes:\n" . join("\n", map { "$_ => ".
}
$imap->logout();
exit $status{CRITICAL};
}
# search for messages
my $tries = 0;
my @msgs;
until( scalar(@msgs) != 0 || $tries >= $max_retries ) {
eval {
$imap->select( $mailbox );
# if download flag is on, we download recent messages and search ourselves
if( $download ) {
print "downloading messages to search\n" if $verbose > 2;
@msgs = download_and_search($imap,@search);
}
else {
print "searching on server\n" if $verbose > 2;
@msgs = $imap->search(@search);
die "Invalid search parameters: $@" if $@;
}
};
if( $@ ) {
chomp $@;
print "Cannot search messages: $@\n";
$imap->close();
$imap->logout();
exit $status{UNKNOWN};
}
$report->{found} = scalar(@msgs);
$tries++;
sleep $interval unless (scalar(@msgs) != 0 || $tries >= $max_retries);
}
sub download_and_search {
my ($imap,@search) = @_;
my $ims = new ImapMessageSearch;
$ims->querytokens(@search);
my @found = ();
@msgs = reverse $imap->messages or (); # die "Cannot list messages: $@\n"; # reversing to get descending order, which is most recent messages first! (at least on my mail servers)
@msgs = @msgs[0..$download_max-1] if $download_max && scalar(@msgs) > $download_max;
foreach my $m (@msgs) {
my $message = $imap->message_string($m);
push @found, $m if $ims->match($message);
}
return @found;
}
# capture data in messages
my $captured_max_id = "";
my $captured_min_id = "";
if( $capture_max || $capture_min ) {
my $max = undef;
my $min = undef;
my %captured = ();
for (my $i=0;$i < scalar(@msgs); $i++) {
my $message = $imap->message_string($msgs[$i]);
if( $message =~ m/$capture_max/ ) {
if( !defined($max) || $1 > $max ) {
$captured{ $i } = 1;
$max = $1;
$captured_max_id = $msgs[$i];
}
}
if( $message =~ m/$capture_min/ ) {
if( !defined($min) || $1 < $min ) {
$captured{ $i } = 1;
$min = $1;
$captured_min_id = $msgs[$i];
}
}
print $message if $verbose > 1;
}
$report->{captured} = scalar keys %captured;
$report->{max} = $max if defined $max;
$report->{min} = $min if defined $min;
}
# delete messages
if( $delete ) {
print "deleting matching messages\n" if $verbose > 2;
my $deleted = 0;
for (my $i=0;$i < scalar(@msgs); $i++) {
next if ($no_delete_captured && ($captured_max_id eq $msgs[$i]));
next if ($no_delete_captured && ($captured_min_id eq $msgs[$i]));
$imap->delete_message($msgs[$i]);
$deleted++;
}
$report->{deleted} = $deleted;
$imap->expunge() if $deleted;
}
# deselect the mailbox
$imap->close();
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
$report->{found} = 0 unless defined $report->{found};
$report->{captured} = 0 unless defined $report->{captured};
my @warning = ();
my @critical = ();
push @warning, "found less than $search_warning_min" if( scalar(@msgs) < $search_warning_min );
push @warning, "found more than $search_warning_max" if ( $search_warning_max > -1 && scalar(@msgs) > $search_warning_max );
push @critical, "found less than $search_critical_min" if ( scalar(@msgs) < $search_critical_min );
push @critical, "found more than $search_critical_max" if ( $search_critical_max > -1 && scalar(@msgs) > $search_critical_max );
push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
# print report and exit with known status
my $perf_data = "elapsed=".$report->{seconds}."s found=".$report->{found}."messages captured=".$report->{captured}."messages"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
my $short_report = $report->text(qw/seconds found captured max min deleted/) . " | $perf_data";
if( scalar @critical ) {
my $crit_alerts = join(", ", @critical);
print "IMAP RECEIVE CRITICAL - $crit_alerts; $short_report\n";
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $warn_alerts = join(", ", @warning);
print "IMAP RECEIVE WARNING - $warn_alerts; $short_report\n";
exit $status{WARNING};
}
print "IMAP RECEIVE OK - $short_report\n";
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package ImapMessageSearch;
require Email::Simple;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{querystring} = [];
$self->{querytokens} = [];
$self->{queryfnlist} = [];
$self->{mimemessage} = undef;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub querystring {
my ($self,$string) = @_;
$self->{querystring} = $string;
return $self->querytokens( parseimapsearch($string) );
}
sub querytokens {
my ($self,@tokens) = @_;
$self->{querytokens} = [@tokens];
$self->{queryfnlist} = [create_search_expressions(@tokens)];
return $self;
}
sub match {
my ($self,$message_string) = @_;
return 0 unless defined $message_string;
my $message_mime = Email::Simple->new($message_string);
return $self->matchmime($message_mime);
}
sub matchmime {
my ($self,$message_mime) = @_;
my $match = 1;
foreach my $x (@{$self->{queryfnlist}}) {
$match = $match && $x->($message_mime);
}
return $match;
}
# this should probably become its own Perl module... see also Net::IMAP::Server::Command::Search
sub create_search_expressions {
my (@search) = @_;
return () unless scalar(@search);
my $token = shift @search;
if( $token eq 'TEXT' ) {
my $value = shift @search;
return (sub {shift->as_string =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'BODY' ) {
my $value = shift @search;
return (sub {shift->body =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'SUBJECT' ) {
my $value = shift @search;
return (sub {shift->header('Subject') =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'HEADER' ) {
my $name = shift @search;
my $value = shift @search;
return (sub {shift->header($name) =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'NOT' ) {
my @exp = create_search_expressions(@search);
my $next = shift @exp;
return (sub { ! $next->(@_) }, @exp);
}
if( $token eq 'OR' ) {
my @exp = create_search_expressions(@search);
my $next1 = shift @exp;
my $next2 = shift @exp;
return (sub { $next1->(@_) or $next2->(@_) }, @exp);
}
if( $token eq 'SENTBEFORE' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) < 0},create_search_expressions(@search));
}
if( $token eq 'SENTON' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) == 0},create_search_expressions(@search));
}
if( $token eq 'SENTSINCE' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) > 0},create_search_expressions(@search));
}
return sub { die "invalid search parameter: $token" };
}
sub datecmp {
my ($date1,$date2) = @_;
my $parsed1 = Date::Manip::ParseDate($date1);
my $parsed2 = Date::Manip::ParseDate($date2);
my $cmp = Date::Manip::Date_Cmp($parsed1,$parsed2);
print " $date1 <=> $date2 -> $cmp\n";
return $cmp <=> 0;
}
package ImapSearchTemplate;
# Takes an English date specification ("now", etc) and an optional offset ("-4 hours")
# and returns an RFC 2822 formatted date string.
# see http://search.cpan.org/dist/Date-Manip/lib/Date/Manip.pod
sub rfc2822dateHeader {
my ($when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, "%a, %d %b %Y %H:%M:%S %z");
}
sub rfc2822date {
my ($when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, "%d-%b-%Y");
}
# alias for 2822 ... RFC 822 is an older version and specifies 2-digit years, but we ignore that for now.
sub rfc822dateHeader { return rfc2822dateHeader(@_); }
sub rfc822date { return rfc2822date(@_); }
sub date {
my ($format,$when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, $format);
}
package main;
1;
__END__
=pod
=head1 NAME
check_imap_receive - connects to and searches an IMAP account for messages
=head1 SYNOPSIS
check_imap_receive -vV
check_imap_receive -?
check_imap_receive --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the IMAP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical <messages>
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --imap-check-interval <seconds>
How long to wait after searching for a matching message before searching again. Only takes effect
if no messages were found. Default is 5 seconds.
=item --imap-retries <number>
How many times to try searching for a matching message before giving up. If you set this to 0 then
messages will not be searched at all. Setting this to 1 means the plugin only tries once. Etc.
Default is 10 times.
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
=item --mailbox <mailbox>
Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m <mailbox>
=item --search <string>
Use this option to filter the messages. Default is not to filter. You may (must) use this option
multiple times in order to create any valid IMAP search criteria. See the examples and see also
http://www.ietf.org/rfc/rfc2060.txt (look for section 6.4.4, the SEARCH command)
This is the way to find messages matching a given subject:
-s SUBJECT -s "a given subject"
You can use the following technique for any header, including Subject. To find "Header-Name: some value":
-s HEADER -s Header-Name -s "some value"
Modern IMAP servers that support rfc5032 extensions allow you to search for messages
older or younger than a number of seconds. So to find messages received in the past hour,
you can do:
-s YOUNGER -s 3600
Or to find messages received more than 5 minutes ago, you can do:
-s OLDER -s 300
Also known as: -s <string>
=item --download
=item --nodownload
This option causes all messages in the specified mailbox to be downloaded from the server
and searched locally. See --download-max if you only want to download a few messages.
Currently only the following RFC 2060 search criteria are supported:
TEXT, BODY, SUBJECT, HEADER, NOT, OR, SENTBEFORE, SENTON, SENTSINCE.
Requires Email::Simple to be installed. It is available on CPAN.
This option may be particularly useful to you if your mail server is slow to index
messages (like Exchange 2003), causing the plugin not to find them with IMAP SEARCH
even though they are in the inbox.
It's also useful if you're searching for messages that have been on the server for a
specified amount of time, like some minutes or hours, because the standard IMAP search
function only allows whole dates. For this, use the standard search keywords but you
can specify either just a date like in RFC 2060 or a date and a time.
If you use SENTBEFORE, SENTON, or SENTSINCE, you must have Date::Manip installed
on your system.
=item --download-max
Limits the number of messages downloaded from the server when the --download option is used.
Default is to download and search all messages.
=item --search-critical-min <messages>
This option will trigger a CRITICAL status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.
This parameter defaults to 1 so that if no messages are found, the plugin will exit with a CRITICAL status.
If you want the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0.
=item --search-critical-max <messages>
This option will trigger a CRITICAL status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.
This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
CRITICAL if it finds 11 messages. If you set it to 1, the plugin will exit with CRITICAL if it finds
any more than 1 message. If you set it to 0, the plugin will exit with CRITICAL if it finds any messages
at all. If you set it to -1 it will be disabled.
=item --search-warning-min <messages>
This option will trigger a WARNING status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.
This parameter defaults to 1 so that if no messages are found, the plugin will exit with a WARNING status.
If you want to suppress the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0. When this parameter is 0, it means that you expect the mailbox not to have any messages.
=item --search-warning-max <messages>
This option will trigger a WARNING status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.
This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
WARNING if it finds 11 messages. If you set it to 1, the plugin will exit with WARNING if it finds
any more than 1 message. If you set it to 0, the plugin will exit with WARNING if it finds any messages
at all. If you set it to -1 it will be disabled.
=item --capture-max <regexp>
In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a "capture-max" regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the highest captured value.
The regexp is expected to capture a numeric value.
=item --capture-min <regexp>
In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a "capture-min" regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the lowest captured value.
The regexp is expected to capture a numeric value.
=item --delete
=item --nodelete
Use the delete option to delete messages that matched the search criteria. This is useful for
preventing the mailbox from filling up with automated messages (from the check_smtp_send plugin, for example).
THE DELETE OPTION IS TURNED *ON* BY DEFAULT, in order to preserve compatibility with an earlier version.
Use the nodelete option to turn off the delete option.
=item --nodelete-captured
If you use both the capture-max and delete arguments, you can also use the nodelete-captured argument to specify that the email
with the highest captured value should not be deleted. This leaves it available for comparison the next time this plugin runs.
If you do not use the delete option, this option has no effect.
=item --ssl
=item --nossl
Enable SSL protocol. Requires IO::Socket::SSL.
Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.
Use the nossl option to turn off the ssl option.
=item --ssl-ca-file
Use this to verify the server SSL certificate against a local .pem file. You'll need to
specify the path to the .pem file as the parameter.
You can use the imap_ssl_cert utility included in this distribution to connect to your IMAP
server and save its SSL certificates into your .pem file. Usage is like this:
imap_ssl_cert -H imap.server.com > ca_file.pem
Only applicable when --ssl option is enabled.
=item --template
=item --notemplate
Enable (or disable) processing of IMAP search parameters. Requires Text::Template and Date::Manip.
Use this option to apply special processing to IMAP search parameters that allows you to use the
results of arbitrary computations as the parameter values. For example, you can use this feature
to search for message received up to 4 hours ago.
Modern IMAP servers that support rfc5032 extensions allow searching with the YOUNGER and OLDER
criteria so a message received up to 4 hours ago is -s YOUNGER -s 14400. But if your mail server
doesn't support that, you could use the --template option to get similar functionality.
When you enable the --template option, each parameter you pass to the -s option is parsed by
Text::Template. See the Text::Template manual for more information, but in general any expression
written in Perl will work.
A convenience function called rfc2822dateHeader is provided to you so you can easily compute properly
formatted dates for use as search parameters. The rfc2822date function can take one or two
parameters itself: the date to format and an optional offset. To use the current time as a
search parameter, you can write this:
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{rfc2822dateHeader("now")}'
The output of {rfc2822dateHeader("now")} looks like this: Wed, 30 Sep 2009 22:44:03 -0700 and
is suitable for use with a date header, like HEADER Delivery-Date.
To use a time in the past relative to the current time or day, you can use a second convenience function
called rfc2822date and write this:
$ check_imap_receive ... --template -s SENTSINCE -s '{rfc2822date("now","-1 day")}'
The output of {rfc2822date("now","-1 day")} looks like this: 29-Sep-2009 and is suitable for use
with BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, and SINCE.
I have seen some email clients use a different format in the Date field,
like September 17, 2009 9:46:51 AM PDT. To specify an arbitrary format like this one, write this:
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{date("%B %e, %Y %i:%M:%S %p %Z","now","-4 hours")}'
You can use BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, or SINCE to search for messages that arrived
on, before, or after a given day but not on, before, or after a specific time on that day.
To search for messages that arrived on, before, or after a specific time you have to use the
Delivery-Date or another date field, like with -s HEADER -s Delivery-Date in the example above.
See the Date::Manip manual for more information on the allowed expressions for date and delta strings.
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Report how many emails are in the mailbox
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete
IMAP RECEIVE OK - 1 seconds, 7 found
=head2 Report the email with the highest value
Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: <auto-000000992528@server.net>
Homeruns 5
And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s "Results of Autoscript" --capture-max "Homeruns (\d+)" --nodelete-captured
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted
=head2 Troubleshoot your search parameters
Add the --nodelete and --imap-retries=1 parameters to your command line.
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 SEE ALSO
http://nagios.org/
http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod
http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod
=head1 CHANGES
Wed Oct 29 11:00:00 PST 2005
+ version 0.1
Wed Nov 9 09:53:32 PST 2005
+ added delete/nodelete option. deleting found messages is still default behavior.
+ added capture-max option
+ added nodelete-captured option
+ added mailbox option
+ added eval/alarm block to implement -c option
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson <johann (at) axis.com>)
+ version 0.2.1
+ added support for multiple polls of imap-server, with specified intervals
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ added patch from Benjamin Ritcey <ben@ritcey.com> for SSL support on machines that have an SSL-enabled
+ version 0.2.3
Fri Apr 27 18:56:50 PDT 2007
+ fixed problem that "Invalid search parameters" was not printed because of missing newline to flush it
+ warnings and critical errors now try to append error messages received from the IMAP client
+ changed connection error to display timeout only if timeout was the error
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ added abbreviations U for username, P for password, m for mailbox
+ fixed bug that imap-check-interval applied even after the last try (imap-retries) when it was not necessary
+ the IMAP expunge command is not sent unless at least one message is deleted
+ fixed bug that the "no messages" warning was printed even if some messages were found
+ version 0.3
Sun Oct 21 14:08:07 PDT 2007
+ added port info to the "could not connect" error message
+ fixed bug that occurred when using --ssl --port 143 which caused port to remain at the default 993 imap/ssl port
+ added clarity shortcuts --search-subject and --search-header
+ port is no longer a required option. defaults to 143 for regular IMAP and 993 for IMAP/SSL
+ version 0.3.1
Sun Oct 21 20:41:56 PDT 2007
+ reworked ssl support to use IO::Socket::SSL instead of the convenience method Mail::IMAPClient->Ssl (which is not included in the standard Mail::IMAPClient package)
+ removed clarity shortcuts (bad idea, code bloat)
+ version 0.4
Tue Dec 4 07:05:27 PST 2007
+ added version check to _read_line workaround for SSL-related bug in Mail::IMAPClient version 2.2.9 ; newer versions fixed the bug
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.1
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.4.2
Mon Jan 7 21:35:23 PST 2008
+ changed version check for Mail::IMAPClient version 2.2.9 to use string comparison le "2.2.9"
+ fixed bug where script was dying on socket->autoflush when socket does not exist because autoflush was being called before checking the socket object
+ version 0.4.3
Mon Feb 11 19:13:38 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.4.4
Mon May 26 08:33:27 PDT 2008
+ fixed a bug for number captured, it now reflects number of messages captured instead of always returning "1"
+ added --capture-min option to complement --capture-max
+ added --search-critical-min to trigger a CRITICAL alert if number of messages found is less than argument, with default 1.
+ fixed warning and critical messages to use "more than" or "less than" instead of the angle brackets, to make them more web friendly
+ version 0.5
Wed Jul 2 14:59:05 PDT 2008
+ fixed a bug for not finding a message after the first try, by reselecting the mailbox before each search
+ version 0.5.1
Sat Dec 13 08:57:29 PST 2008
+ added --download option to allow local searching of messages (useful if your server has an index that handles searching but it takes a while before new emails show up and you want immediate results), supports only the TEXT, BODY, SUBJECT, and HEADER search keys
+ added --download-max option to set a limit on number of messages downloaded with --download
+ version 0.6.0
Wed Sep 30 23:25:33 PDT 2009
+ fixed --download-max option (was incorrectly looking for --download_max). currently both will work, in the future only --download-max will work
+ added --template option to allow arbitrary substitutions for search parameters, and provided three convenience functions for working with dates
+ added date search criteria to the --download option: SENTBEFORE, SENTON, and SENTSINCE which check the Date header and allow hours and minutes in addition to dates (whereas the IMAP standard only allows dates)
+ added --search-critical-max to trigger a CRITICAL alert if number of messages found is more than argument, disabled by default.
+ fixed a bug in --download --search where messages would match even though they failed the search criteria
+ changed behavior of --download-max to look at the most recent messages first (hopefully); the IMAP protocol doesn't guarantee the order that the messages are returned but I observed that many mail servers return them in chronological order; so now --download-max reverses the order to look at the newer messages first
+ added performance data for use with PNP4Nagios!
+ version 0.7.0
Fri Oct 2 15:22:00 PDT 2009
+ added --search-warning-max and --search-warning-min to trigger a WARNING alert if number of messages is more than or less than the specified number.
+ fixed --download option not to fail with CRITICAL if mailbox is empty; now this can be configured with --search-warning-min or --search-critical-min
+ version 0.7.1
Sat Nov 21 18:27:17 PST 2009
+ fixed problem with using --download option on certain mail servers by turning on the IgnoreSizeErrors feature in IMAPClient
+ added --peek option to prevent marking messages as seen
+ version 0.7.2
Tue Jan 5 12:13:53 PST 2010
+ added error message and exit with unknown status when an unrecognized IMAP search criteria is encountered by the --download --search option
Wed May 5 11:14:51 PDT 2010
+ added mailbox list when mailbox is not found and verbose level 3 is on (-vvv)
+ version 0.7.3
Tue Mar 8 18:58:14 AST 2011
+ updated documentation for --search and --template to mention rfc5032 extensions (thanks to Stuart Henderson)
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.4
Fri Nov 11 01:51:40 AST 2011
+ added --ssl-ca-file option to allow verifying the server certificate against a local .pem file (thanks to Alexandre Bezroutchko)
+ added imap_ssl_cert.pl utility (not in this file) to conveniently save the server's SSL certificates into a local .pem file
+ version 0.7.5
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,492 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.7.5';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Mail::IMAPClient/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $username = "";
my $password = "";
my $mailbox = "INBOX";
my @search = ();
my $search_critical_min = 1;
my $search_critical_max = -1; # -1 means disabled for this option
my $search_warning_min = 1;
my $search_warning_max = -1; # -1 means disabled for this option
my $capture_max = "";
my $capture_min = "";
my $delete = 1;
my $no_delete_captured = "";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $interval = 5;
my $max_retries = 10;
my $download = "";
my $download_max = "";
my $peek = "";
my $template = "";
my $ssl = 0;
my $ssl_ca_file = "";
my $tls = 0;
my $time_hires = "";
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
"U|username=s"=>\$username,"P|password=s"=>\$password, "m|mailbox=s"=>\$mailbox,
"imap-check-interval=i"=>\$interval,"imap-retries=i"=>\$max_retries,
"ssl!"=>\$ssl, "ssl-ca-file=s"=>\$ssl_ca_file, "tls!"=>\$tls,
# search settings
"s|search=s"=>\@search,
"search-critical-min=i"=>\$search_critical_min, "search-critical-max=i"=>\$search_critical_max,
"search-warning-min=i"=>\$search_warning_min, "search-warning-max=i"=>\$search_warning_max,
"capture-max=s"=>\$capture_max, "capture-min=s"=>\$capture_min,
"delete!"=>\$delete, "nodelete-captured"=>\$no_delete_captured,
"download!"=>\$download, "download_max=i"=>\$download_max, "download-max=i"=>\$download_max,
"peek!"=>\$peek,
"template!"=>\$template,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
my @required_module = ();
push @required_module, 'IO::Socket::SSL' if $ssl || $tls;
push @required_module, 'Email::Simple' if $download;
push @required_module, ('Text::Template','Date::Manip') if $template;
exit $status{UNKNOWN} unless load_modules(@required_module);
if( $help_usage
||
( $imap_server eq "" || $username eq "" || $password eq "" || scalar(@search)==0 )
) {
print "Usage: $0 -H host [-p port] -U username -P password -s HEADER -s X-Nagios -s 'ID: 1234.' [-w <seconds>] [-c <seconds>] [--imap-check-interval <seconds>] [--imap-retries <tries>]\n";
exit $status{UNKNOWN};
}
# before attempting to connect to the server, check if any of the search parameters
# use substitution functions and make sure we can parse them first. if we can't we
# need to abort since the search will be meaningless.
if( $template ) {
foreach my $token (@search) {
my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$token,PACKAGE=>'ImapSearchTemplate');
$token = $t->fill_in(PREPEND=>q{package ImapSearchTemplate;});
#print "token: $token\n";
}
}
# initialize
my $report = new PluginReport;
my $time_start = time;
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
if( $ssl || $tls ) {
$imap_port = $default_imap_ssl_port unless $imap_port;
my %ssl_args = ();
if( length($ssl_ca_file) > 0 ) {
$ssl_args{SSL_verify_mode} = 1;
$ssl_args{SSL_ca_file} = $ssl_ca_file;
$ssl_args{SSL_verifycn_scheme} = 'imap';
$ssl_args{SSL_verifycn_name} = $imap_server;
}
my $socket = IO::Socket::SSL->new(PeerAddr=>"$imap_server:$imap_port", %ssl_args);
die IO::Socket::SSL::errstr() . " (if you get this only when using both --ssl and --ssl-ca-file, but not when using just --ssl, the server SSL certificate failed validation)" unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
$imap->User($username);
$imap->Password($password);
$imap->login() or die "Cannot login: $@";
}
else {
$imap_port = $default_imap_port unless $imap_port;
$imap = Mail::IMAPClient->new(Debug => 0 );
$imap->Server("$imap_server:$imap_port");
$imap->User($username);
$imap->Password($password);
$imap->connect() or die "$@";
}
$imap->Peek(1) if $peek;
$imap->Ignoresizeerrors(1);
alarm 0;
};
if( $@ ) {
chomp $@;
print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "IMAP RECEIVE CRITICAL - Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
my $time_connected = time;
# select a mailbox
print "selecting mailbox $mailbox\n" if $verbose > 2;
unless( $imap->select($mailbox) ) {
print "IMAP RECEIVE CRITICAL - Could not select $mailbox: $@ $!\n";
if( $verbose > 2 ) {
print "Mailbox list:\n" . join("\n", $imap->folders) . "\n";
print "Mailbox separator: " . $imap->separator . "\n";
##print "Special mailboxes:\n" . join("\n", map { "$_ => ".
}
$imap->logout();
exit $status{CRITICAL};
}
# search for messages
my $tries = 0;
my @msgs;
until( scalar(@msgs) != 0 || $tries >= $max_retries ) {
eval {
$imap->select( $mailbox );
# if download flag is on, we download recent messages and search ourselves
if( $download ) {
print "downloading messages to search\n" if $verbose > 2;
@msgs = download_and_search($imap,@search);
}
else {
print "searching on server\n" if $verbose > 2;
@msgs = $imap->search(@search);
die "Invalid search parameters: $@" if $@;
}
};
if( $@ ) {
chomp $@;
print "Cannot search messages: $@\n";
$imap->close();
$imap->logout();
exit $status{UNKNOWN};
}
$report->{found} = scalar(@msgs);
$tries++;
sleep $interval unless (scalar(@msgs) != 0 || $tries >= $max_retries);
}
sub download_and_search {
my ($imap,@search) = @_;
my $ims = new ImapMessageSearch;
$ims->querytokens(@search);
my @found = ();
@msgs = reverse $imap->messages or (); # die "Cannot list messages: $@\n"; # reversing to get descending order, which is most recent messages first! (at least on my mail servers)
@msgs = @msgs[0..$download_max-1] if $download_max && scalar(@msgs) > $download_max;
foreach my $m (@msgs) {
my $message = $imap->message_string($m);
push @found, $m if $ims->match($message);
}
return @found;
}
# capture data in messages
my $captured_max_id = "";
my $captured_min_id = "";
if( $capture_max || $capture_min ) {
my $max = undef;
my $min = undef;
my %captured = ();
for (my $i=0;$i < scalar(@msgs); $i++) {
my $message = $imap->message_string($msgs[$i]);
if( $message =~ m/$capture_max/ ) {
if( !defined($max) || $1 > $max ) {
$captured{ $i } = 1;
$max = $1;
$captured_max_id = $msgs[$i];
}
}
if( $message =~ m/$capture_min/ ) {
if( !defined($min) || $1 < $min ) {
$captured{ $i } = 1;
$min = $1;
$captured_min_id = $msgs[$i];
}
}
print $message if $verbose > 1;
}
$report->{captured} = scalar keys %captured;
$report->{max} = $max if defined $max;
$report->{min} = $min if defined $min;
}
# delete messages
if( $delete ) {
print "deleting matching messages\n" if $verbose > 2;
my $deleted = 0;
for (my $i=0;$i < scalar(@msgs); $i++) {
next if ($no_delete_captured && ($captured_max_id eq $msgs[$i]));
next if ($no_delete_captured && ($captured_min_id eq $msgs[$i]));
$imap->delete_message($msgs[$i]);
$deleted++;
}
$report->{deleted} = $deleted;
$imap->expunge() if $deleted;
}
# deselect the mailbox
$imap->close();
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
$report->{found} = 0 unless defined $report->{found};
$report->{captured} = 0 unless defined $report->{captured};
my @warning = ();
my @critical = ();
push @warning, "found less than $search_warning_min" if( scalar(@msgs) < $search_warning_min );
push @warning, "found more than $search_warning_max" if ( $search_warning_max > -1 && scalar(@msgs) > $search_warning_max );
push @critical, "found less than $search_critical_min" if ( scalar(@msgs) < $search_critical_min );
push @critical, "found more than $search_critical_max" if ( $search_critical_max > -1 && scalar(@msgs) > $search_critical_max );
push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
# print report and exit with known status
my $perf_data = "elapsed=".$report->{seconds}."s found=".$report->{found}."messages captured=".$report->{captured}."messages"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
my $short_report = $report->text(qw/seconds found captured max min deleted/) . " | $perf_data";
if( scalar @critical ) {
my $crit_alerts = join(", ", @critical);
print "IMAP RECEIVE CRITICAL - $crit_alerts; $short_report\n";
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $warn_alerts = join(", ", @warning);
print "IMAP RECEIVE WARNING - $warn_alerts; $short_report\n";
exit $status{WARNING};
}
print "IMAP RECEIVE OK - $short_report\n";
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package ImapMessageSearch;
require Email::Simple;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{querystring} = [];
$self->{querytokens} = [];
$self->{queryfnlist} = [];
$self->{mimemessage} = undef;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub querystring {
my ($self,$string) = @_;
$self->{querystring} = $string;
return $self->querytokens( parseimapsearch($string) );
}
sub querytokens {
my ($self,@tokens) = @_;
$self->{querytokens} = [@tokens];
$self->{queryfnlist} = [create_search_expressions(@tokens)];
return $self;
}
sub match {
my ($self,$message_string) = @_;
return 0 unless defined $message_string;
my $message_mime = Email::Simple->new($message_string);
return $self->matchmime($message_mime);
}
sub matchmime {
my ($self,$message_mime) = @_;
my $match = 1;
foreach my $x (@{$self->{queryfnlist}}) {
$match = $match && $x->($message_mime);
}
return $match;
}
# this should probably become its own Perl module... see also Net::IMAP::Server::Command::Search
sub create_search_expressions {
my (@search) = @_;
return () unless scalar(@search);
my $token = shift @search;
if( $token eq 'TEXT' ) {
my $value = shift @search;
return (sub {shift->as_string =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'BODY' ) {
my $value = shift @search;
return (sub {shift->body =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'SUBJECT' ) {
my $value = shift @search;
return (sub {shift->header('Subject') =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'HEADER' ) {
my $name = shift @search;
my $value = shift @search;
return (sub {shift->header($name) =~ /\Q$value\E/i},create_search_expressions(@search));
}
if( $token eq 'NOT' ) {
my @exp = create_search_expressions(@search);
my $next = shift @exp;
return (sub { ! $next->(@_) }, @exp);
}
if( $token eq 'OR' ) {
my @exp = create_search_expressions(@search);
my $next1 = shift @exp;
my $next2 = shift @exp;
return (sub { $next1->(@_) or $next2->(@_) }, @exp);
}
if( $token eq 'SENTBEFORE' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) < 0},create_search_expressions(@search));
}
if( $token eq 'SENTON' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) == 0},create_search_expressions(@search));
}
if( $token eq 'SENTSINCE' ) {
my $value = shift @search;
return (sub {datecmp(shift->header('Date'),$value) > 0},create_search_expressions(@search));
}
return sub { die "invalid search parameter: $token" };
}
sub datecmp {
my ($date1,$date2) = @_;
my $parsed1 = Date::Manip::ParseDate($date1);
my $parsed2 = Date::Manip::ParseDate($date2);
my $cmp = Date::Manip::Date_Cmp($parsed1,$parsed2);
print " $date1 <=> $date2 -> $cmp\n";
return $cmp <=> 0;
}
package ImapSearchTemplate;
# Takes an English date specification ("now", etc) and an optional offset ("-4 hours")
# and returns an RFC 2822 formatted date string.
# see http://search.cpan.org/dist/Date-Manip/lib/Date/Manip.pod
sub rfc2822dateHeader {
my ($when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, "%a, %d %b %Y %H:%M:%S %z");
}
sub rfc2822date {
my ($when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, "%d-%b-%Y");
}
# alias for 2822 ... RFC 822 is an older version and specifies 2-digit years, but we ignore that for now.
sub rfc822dateHeader { return rfc2822dateHeader(@_); }
sub rfc822date { return rfc2822date(@_); }
sub date {
my ($format,$when,$delta) = @_;
$when = Date::Manip::ParseDate($when);
$delta = Date::Manip::ParseDateDelta($delta) if $delta;
my $d = $delta ? Date::Manip::DateCalc($when,$delta) : $when;
return Date::Manip::UnixDate($d, $format);
}
package main;
1;

View File

@ -0,0 +1,782 @@
#!/usr/bin/perl
use strict;
use POSIX qw(strftime);
my $VERSION = '0.7.3';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Net::SMTP/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $smtp_server = "";
my $default_smtp_port = "25";
my $default_smtp_ssl_port = "465";
my $default_smtp_tls_port = "587";
my $smtp_port = "";
my @mailto = ();
my $mailfrom = "";
my @header = ();
my $body = "";
my $stdin = "";
my $template = "";
my $expect_response = "250";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $tls = 0;
my $ssl = 0;
my $auth_method = undef;
my $username = "";
my $password = "";
my $time_hires = "";
my $mx_lookup = 0;
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# smtp settings
"H|hostname=s"=>\$smtp_server,"p|port=i"=>\$smtp_port,
"mailto=s"=>\@mailto, "mailfrom=s",\$mailfrom,
"header=s"=>\@header, "body=s"=>\$body, "stdin"=>\$stdin,
"template!"=>\$template,
# SSL/TLS/auth options
"tls!"=>\$tls, "ssl!"=>\$ssl, "auth=s"=>\$auth_method,
"U|username=s"=>\$username,"P|password=s"=>\$password,
# Server response
"E|expect-response=s"=>\$expect_response,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $smtp_server eq "" && scalar(@mailto) == 1 ) {
# no SMTP server specified but one mailto address given means we can look up the MX record
$mx_lookup = 1;
}
my @required_module = ();
push @required_module, 'Net::SMTP::SSL' if $ssl;
push @required_module, ('MIME::Base64','Authen::SASL') if $ssl && $username;
push @required_module, 'Net::SMTP::TLS' if $tls;
push @required_module, 'Net::SMTP_auth' if $auth_method and not $tls; # whereas if auth_method and tls we use TLS_auth, which is included in this script!
push @required_module, 'Text::Template' if $template;
push @required_module, 'Net::DNS' if $mx_lookup;
push @required_module, 'Email::Address' if $mx_lookup;
exit $status{UNKNOWN} unless load_modules(@required_module);
# split up @mailto if commas were used instead of multiple options
@mailto = split(/,/,join(',',@mailto));
if( $help_usage ||
(
($smtp_server eq "" && !$mx_lookup) || scalar(@mailto)==0 || $mailfrom eq ""
)
) {
print "Usage: $0 [-H host [-p port]] --mailto recipient\@your.net [--mailto recipient2\@your.net ...] --mailfrom sender\@your.net --body 'some text' [-w <seconds>] [-c <seconds>]\n";
exit $status{UNKNOWN};
}
# initialize
my $report = new PluginReport;
my $time_start = time;
my $actual_response = undef;
my @warning = ();
my @critical = ();
my $smtp_debug = 0;
$smtp_debug = 1 if $verbose >= 3;
# default date and message id headers
push @header, default_date_header() unless find_header("Date",@header);
push @header, default_messageid_header() unless find_header("Message-ID",@header);
# look up MX server if necessary
if( $mx_lookup ) {
my $addr = Email::Address->new( undef, $mailto[0] );
my $mx_domain = $addr->host;
print "MX lookup " . $mx_domain . "\n" if $verbose > 1;
my $res = Net::DNS::Resolver->new;
my @mx = Net::DNS::mx($res, $mx_domain);
if( @mx ) {
# use the first server
foreach my $rr (@mx) {
print "pref : " . $rr->preference . " exchange: " . $rr->exchange . "\n" if $verbose > 2;
}
$smtp_server = $mx[0]->exchange;
print "smtp server: $smtp_server\n" if $verbose;
}
else {
print "SMTP SEND CRITICAL - Cannot find MX records for $mx_domain\n";
exit $status{CRITICAL};
}
}
# connect to SMTP server
# create the smtp handle using Net::SMTP, Net::SMTP::SSL, Net::SMTP::TLS, or an authentication variant
my $smtp;
eval {
if( $tls and $auth_method ) {
$smtp_port = $default_smtp_tls_port unless $smtp_port;
$smtp = TLS_auth->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password, Auth_Method=>$auth_method);
if( $smtp ) {
my $message = oneline($smtp->message());
die "cannot connect with TLS/$auth_method: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $tls ) {
$smtp_port = $default_smtp_tls_port unless $smtp_port;
$smtp = Net::SMTP::TLS->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password);
if( $smtp ) {
my $message = oneline($smtp->message());
die "cannot connect with TLS: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $ssl ) {
$smtp_port = $default_smtp_ssl_port unless $smtp_port;
$smtp = Net::SMTP::SSL->new($smtp_server, Port => $smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp && $username ) {
$smtp->auth($username, $password);
my $message = oneline($smtp->message());
die "cannot connect with SSL/password: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $auth_method ) {
$smtp_port = $default_smtp_port unless $smtp_port;
$smtp = Net::SMTP_auth->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp ) {
$smtp->auth($auth_method, $username, $password);
my $message = oneline($smtp->message());
die "cannot connect with SSL/$auth_method: $message" if $smtp->code() =~ m/53\d/;
}
}
else {
$smtp_port = $default_smtp_port unless $smtp_port;
$smtp = Net::SMTP->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp && $username ) {
$smtp->auth($username, $password);
my $message = oneline($smtp->message());
die "cannot connect with password: $message" if $smtp->code() =~ m/53\d/;
}
}
};
if( $@ ) {
$@ =~ s/\n/ /g; # the error message can be multiline but we want our output to be just one line
print "SMTP SEND CRITICAL - $@\n";
exit $status{CRITICAL};
}
unless( $smtp ) {
print "SMTP SEND CRITICAL - Could not connect to $smtp_server port $smtp_port\n";
exit $status{CRITICAL};
}
my $time_connected = time;
# add the monitored server's banner to the report
if( $tls ) {
$report->{banner} = "";
}
elsif( $ssl ) {
$report->{banner} = $smtp->banner || "";
chomp $report->{banner};
}
else {
$report->{banner} = $smtp->banner || "";
chomp $report->{banner};
}
# send email
if( $stdin ) {
$body = "";
while(<STDIN>) {
$body .= $_;
}
}
# if user wants to use template substitutions, this is the place to process body and headers
if( $template ) {
foreach my $item (@header,$body) {
my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$item,PACKAGE=>'SmtpMessageTemplate');
$item = $t->fill_in(PREPEND=>q{package SmtpMessageTemplate;});
# print "item: $item\n";
}
}
$smtp->mail($mailfrom);
foreach( @mailto ) {
# the two SMTP modules have different error reporting mechanisms:
if( $tls ) {
# Net::SMTP::TLS croaks when the recipient is rejected
eval {
$smtp->to($_);
};
if( $@ ) {
print "SMTP SEND CRITICAL - Could not send to $_\n";
print "Reason: $@\n" if $verbose;
exit $status{CRITICAL};
}
}
else {
# Net::SMTP returns false when the recipient is rejected
my $to_returned = $smtp->to($_);
if( !$to_returned ) {
print "SMTP SEND CRITICAL - Could not send to $_\n";
print "Reason: Recipient rejected or authentication failed\n" if $verbose;
exit $status{CRITICAL};
}
}
}
# Net::SMTP::TLS doesn't implement code() so we need to wrap calls in eval to get our error messages
# start data transfer (expect response 354)
$smtp->data();
# send data
$smtp->datasend("To: ".join(", ",@mailto)."\n");
$smtp->datasend("From: $mailfrom\n");
foreach( @header ) {
$smtp->datasend("$_\n");
}
$smtp->datasend("\n");
$smtp->datasend($body);
$smtp->datasend("\n");
eval {
# end data transfer (expect response 250)
$smtp->dataend();
};
if( $@ ) {
$actual_response = $tls ? get_tls_error($@) : $smtp->code();
}
else {
$actual_response = $tls ? "250" : $smtp->code(); # no error means we got 250
}
eval {
# disconnect from SMTP server (expect response 221)
$smtp->quit();
};
if( $@ ) {
push @warning, "Error while disconnecting from $smtp_server";
}
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
push @critical, "response was $actual_response but expected $expect_response" if ( $actual_response ne $expect_response );
# print report and exit with known status
my $perf_data = "elapsed=".$report->{seconds}."s;$warntime;$criticaltime"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
my $short_report = $report->text(qw/seconds/) . " | $perf_data";
my $long_report = join("", map { "$_: $report->{$_}\n" } qw/banner/ );
if( scalar @critical ) {
my $crit_alerts = join(", ", @critical);
print "SMTP SEND CRITICAL - $crit_alerts; $short_report\n";
print $long_report if $verbose;
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $warn_alerts = join(", ", @warning);
print "SMTP SEND WARNING - $warn_alerts; $short_report\n";
print $long_report if $verbose;
exit $status{WARNING};
}
print "SMTP SEND OK - $short_report\n";
print $long_report if $verbose;
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# utility to extract error codes out of Net::SMTP::TLS croak messages
sub get_tls_error {
my ($errormsg) = @_;
$errormsg =~ m/: (\d+) (.+)/;
my $code = $1;
return $code;
}
# looks for a specific header in a list of headers; returns true if found
sub find_header {
my ($name, @list) = @_;
return scalar grep { m/^$name: /i } @list;
}
# RFC 2822 date header
sub default_date_header {
return strftime "Date: %a, %e %b %Y %H:%M:%S %z (%Z)", gmtime;
}
# RFC 2822 message id header
sub default_messageid_header {
my $random = randomstring(16,qw/0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z/);
my $hostname = `hostname`;
chomp $hostname;
return "Message-ID: <".time.".".$random.".checksmtpsend@".$hostname.">";
}
# returns a random string of specified length using characters from specified set
sub randomstring {
my ($length,@set) = @_;
my $size = scalar @set;
my $string = "";
while($length--) {
$string .= $set[int(rand($size))];
}
return $string;
}
# replaces all newlines in the input string with spaces
sub oneline {
my ($input) = @_;
$input =~ s/[\r\n]+/ /g;
return $input;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package SmtpMessageTemplate;
sub trim {
my ($text) = @_;
$text =~ s/^\s*//;
$text =~ s/\s*$//;
return $text;
}
# NAME
# TLS_auth
# SYNOPSYS
#
# Based on contribution by Brad Guillory
package TLS_auth;
#use Net::SMTP::TLS;
our @ISA = qw(Net::SMTP::TLS);
use Carp;
sub new {
my ($proto,$server,%p) = @_;
my $class = ref($proto) || $proto;
#my $self = bless {}, $class;
no strict 'refs';
no warnings 'once';
*Net::SMTP::TLS::login = *TLS_auth::login; # override parent's login with ours so when it's called in the constructor, our overriden version will be used
my $self = Net::SMTP::TLS->new($server,%p);
return $self;
}
sub login {
my ($self) = @_;
my $type = $self->{features}->{AUTH};
if(not $type){
die "Server did not return AUTH in capabilities\n"; # croak
}
# print "Feature: $type\nAuth Method: $self->{Auth_Method}\n";
if($type =~ /CRAM\-MD5/ and $self->{Auth_Method} =~ /CRAM\-MD5/i){
$self->auth_MD5();
}elsif($type =~ /LOGIN/ and $self->{Auth_Method} =~ /LOGIN/i){
$self->auth_LOGIN();
}elsif($type =~ /PLAIN/ and $self->{Auth_Method} =~ /PLAIN/i){
#print "Calling auth_PLAIN\n";
$self->auth_PLAIN();
}else{
die "Unsupported Authentication mechanism: $self->{Auth_Method}\n"; # croak
}
}
package main;
1;
__END__
=pod
=head1 NAME
check_smtp_send - connects to an SMTP server and sends a message
=head1 SYNOPSIS
check_smtp_send -vV
check_smtp_send -?
check_smtp_send --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the SMTP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the SMTP server. Default is 30 seconds.
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the SMTP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the SMTP server. Examples: mail.server.com, localhost, 192.168.1.100
If not provided, and if there is only one --mailto address, the script will automatically look up the MX record
for the --mailto address and use that as the hostname. You can use this to check that your MX records are correct.
When omitting the --hostname option, it doesn't really make sense to specify --port, --username, or --password
but you can still do so and they will have their normal effect. To look up the MX records you need to have the
module Net::DNS and Email::Address installed.
Also known as: -H <server>
=item --port <number>
Service port on the SMTP server. Default is 25 for regular SMTP, 465 for SSL, and 587 for TLS.
Also known as: -p <number>
=item --tls
=item --notls
Enable TLS/AUTH protocol. Requires Net::SMTP::TLS, availble on CPAN.
When using this option, the default port is 587.
You can specify a port from the command line using the --port option.
Use the notls option to turn off the tls option.
Also, you may need to fix your copy of Net::SMTP::TLS. Here is the diff against version 0.12:
254c254
< $me->_command(sprintf("AUTH PLAIN %S",
---
> $me->_command(sprintf("AUTH PLAIN %s",
=item --ssl
=item --nossl
Enable SSL protocol. Requires Net::SMTP::SSL and Authen::SASL, availble on CPAN.
When using this option, the default port is 465. You can override with the --port option.
Use the nossl option to turn off the ssl option.
=item --auth <method>
Enable authentication with Net::SMTP_auth (sold separately).
For example, try using --auth PLAIN or --auth CRAM-MD5.
=item --username <username>
=item --password <password>
Username and password to use when connecting to SMTP server.
Also known as: -U <username> -P <password>
=item --body <message>
Use this option to specify the body of the email message. If you need newlines in your message,
you might need to use the --stdin option instead.
=item --header <header>
Use this option to set an arbitrary header in the message. You can use it multiple times.
=item --stdin
Grab the body of the email message from stdin.
=item --mailto recipient@your.net
You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):
$ check_smtp_send -H mail.server.net --mailto recipient@your.net,recipient2@your.net --mailfrom sender@your.net
SMTP SEND OK - 1 seconds
=item --mailfrom sender@your.net
Use this option to set the "from" address in the email.
=item --template
=item --notemplate
Enable (or disable) processing of message body and headers. Requires Text::Template.
Use this option to apply special processing to your message body and headers that allows you to use the
results of arbitrary computations in the text. For example, you can use this feature to send a message
containing the hostname of the machine that sent the message without customizing the plugin configuration
on each machine.
When you enable the --template option, the message body and headers are parsed by
Text::Template. Even a message body provided using the --stdin option will be parsed.
See the Text::Template manual for more information, but in general any expression
written in Perl will work.
There is one convenience function provided to you, trim, which will remove leading and trailing whitespace
from its parameter. Here's an example:
check_smtp_send -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--template --body 'hello, this message is from {use Sys::Hostname; hostname}'
--header 'Subject: test message from {trim(`whoami`)}'
=item --expect-response <code>
Use this option to specify which SMTP response code should be expected from the server
after the SMTP dialog is complete. The default is 250 (message accepted).
Also known as: -E <code>
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting.
One --verbose will show extra information for OK, WARNING, and CRITICAL status.
Use one --verbose together with --version to see the default warning and critical timeout values.
Three --verbose (or -vvv) will show debug information, unless you're using --tls because Net::SMTP::TLS
does not have a Debug feature.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Send a message with custom headers
$ check_smtp_send -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--body 'Homeruns 5' --header 'Subject: Hello, world!' --header 'X-Your-Header: Yes'
SMTP SEND OK - 1 seconds
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 CHANGES
Wed Oct 29 14:05:00 PST 2005
+ version 0.1
Wed Nov 9 15:01:48 PST 2005
+ now using an inline PluginReport package to generate the report
+ added stdin option
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton <geoff.crompton@strategicdata.com.au>)
+ added bailing if the $smtp->to() call fails
+ added support for mailto recipients separated by commas
+ version 0.2.1
Tue Apr 24 21:17:53 PDT 2007
+ moved POD text to separate file in order to accomodate the new embedded-perl Nagios feature
+ version 0.2.3
Fri Apr 27 20:26:42 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ version 0.3
Sun Oct 21 10:34:14 PDT 2007
+ added support for TLS and authentication via the Net::SMTP::TLS module. see --tls option.
+ version 0.4
Sun Oct 21 13:54:26 PDT 2007
+ added support for SSL via the Net::SMTP::SSL module. see --ssl option.
+ port is no longer a required option. defaults to 25 for regular smtp, 465 for ssl, and 587 for tls.
+ added port info to the "could not connect" error message
+ version 0.4.1
Tue Dec 4 07:42:32 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.2
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.4.3
Mon May 26 09:12:14 PDT 2008
+ fixed warning and critical messages to use "more than" or "less than" instead of the angle brackets, to make them more web friendly
+ version 0.4.4
Wed Jul 2 07:12:35 PDT 2008
+ added --expect-response option submitted by Christian Kauhaus <kc@gocept.com>
+ added support for authentication via Net::SMTP_auth. see --auth option.
+ version 0.4.5
Sun Oct 5 15:18:23 PDT 2008
+ added error handling for smtp server disconnects ungracefully during QUIT (gmail.com does)
+ version 0.4.6
Thu Oct 1 12:09:35 PDT 2009
+ added --template option to allow arbitrary substitutions for body and headers, and provided one convenience function for trimming strings
+ added performance data for use with PNP4Nagios!
+ version 0.5.0
Thu Oct 8 11:17:04 PDT 2009
+ added more detailed error messages when using --verbose
+ version 0.5.1
Tue Feb 9 12:14:49 PST 2010
+ added support for combining --auth with --tls using a subclass of Net::SMTP::TLS submitted by Brad Guillory; please note that to use the "PLAIN" authentication type you need to patch your Net::SMTP:TLS because it has a bug in sub auth_PLAIN (sprintf %S instead of %s)
+ version 0.5.2
Mon Jan 3 10:39:42 PST 2011
+ added default Date and Message-ID headers; Date header uses POSIX strftime and Message-ID header uses hostname command to get localhost name
+ version 0.7.0
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1
Wed Jul 6 19:18:26 AST 2011
+ the --hostname is now optional; if not provided the plugin will lookup the MX record for the --mailto address (requires Net::DNS)
+ version 0.7.2
Tue Dec 13 09:24:04 PST 2011
+ separated authentication errors from connection errors
+ version 0.7.3
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,458 @@
#!/usr/bin/perl
use strict;
use POSIX qw(strftime);
my $VERSION = '0.7.3';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
# look for required modules
exit $status{UNKNOWN} unless load_modules(qw/Getopt::Long Net::SMTP/);
BEGIN {
if( grep { /^--hires$/ } @ARGV ) {
eval "use Time::HiRes qw(time);";
warn "Time::HiRes not installed\n" if $@;
}
}
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $smtp_server = "";
my $default_smtp_port = "25";
my $default_smtp_ssl_port = "465";
my $default_smtp_tls_port = "587";
my $smtp_port = "";
my @mailto = ();
my $mailfrom = "";
my @header = ();
my $body = "";
my $stdin = "";
my $template = "";
my $expect_response = "250";
my $warntime = 15;
my $criticaltime = 30;
my $timeout = 60;
my $tls = 0;
my $ssl = 0;
my $auth_method = undef;
my $username = "";
my $password = "";
my $time_hires = "";
my $mx_lookup = 0;
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
"w|warning=i"=>\$warntime,"c|critical=i"=>\$criticaltime,"t|timeout=i"=>\$timeout,
# smtp settings
"H|hostname=s"=>\$smtp_server,"p|port=i"=>\$smtp_port,
"mailto=s"=>\@mailto, "mailfrom=s",\$mailfrom,
"header=s"=>\@header, "body=s"=>\$body, "stdin"=>\$stdin,
"template!"=>\$template,
# SSL/TLS/auth options
"tls!"=>\$tls, "ssl!"=>\$ssl, "auth=s"=>\$auth_method,
"U|username=s"=>\$username,"P|password=s"=>\$password,
# Server response
"E|expect-response=s"=>\$expect_response,
# Time
"hires"=>\$time_hires,
);
if( $show_version ) {
print "$VERSION\n";
if( $verbose ) {
print "Default warning threshold: $warntime seconds\n";
print "Default critical threshold: $criticaltime seconds\n";
print "Default timeout: $timeout seconds\n";
}
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $smtp_server eq "" && scalar(@mailto) == 1 ) {
# no SMTP server specified but one mailto address given means we can look up the MX record
$mx_lookup = 1;
}
my @required_module = ();
push @required_module, 'Net::SMTP::SSL' if $ssl;
push @required_module, ('MIME::Base64','Authen::SASL') if $ssl && $username;
push @required_module, 'Net::SMTP::TLS' if $tls;
push @required_module, 'Net::SMTP_auth' if $auth_method and not $tls; # whereas if auth_method and tls we use TLS_auth, which is included in this script!
push @required_module, 'Text::Template' if $template;
push @required_module, 'Net::DNS' if $mx_lookup;
push @required_module, 'Email::Address' if $mx_lookup;
exit $status{UNKNOWN} unless load_modules(@required_module);
# split up @mailto if commas were used instead of multiple options
@mailto = split(/,/,join(',',@mailto));
if( $help_usage ||
(
($smtp_server eq "" && !$mx_lookup) || scalar(@mailto)==0 || $mailfrom eq ""
)
) {
print "Usage: $0 [-H host [-p port]] --mailto recipient\@your.net [--mailto recipient2\@your.net ...] --mailfrom sender\@your.net --body 'some text' [-w <seconds>] [-c <seconds>]\n";
exit $status{UNKNOWN};
}
# initialize
my $report = new PluginReport;
my $time_start = time;
my $actual_response = undef;
my @warning = ();
my @critical = ();
my $smtp_debug = 0;
$smtp_debug = 1 if $verbose >= 3;
# default date and message id headers
push @header, default_date_header() unless find_header("Date",@header);
push @header, default_messageid_header() unless find_header("Message-ID",@header);
# look up MX server if necessary
if( $mx_lookup ) {
my $addr = Email::Address->new( undef, $mailto[0] );
my $mx_domain = $addr->host;
print "MX lookup " . $mx_domain . "\n" if $verbose > 1;
my $res = Net::DNS::Resolver->new;
my @mx = Net::DNS::mx($res, $mx_domain);
if( @mx ) {
# use the first server
foreach my $rr (@mx) {
print "pref : " . $rr->preference . " exchange: " . $rr->exchange . "\n" if $verbose > 2;
}
$smtp_server = $mx[0]->exchange;
print "smtp server: $smtp_server\n" if $verbose;
}
else {
print "SMTP SEND CRITICAL - Cannot find MX records for $mx_domain\n";
exit $status{CRITICAL};
}
}
# connect to SMTP server
# create the smtp handle using Net::SMTP, Net::SMTP::SSL, Net::SMTP::TLS, or an authentication variant
my $smtp;
eval {
if( $tls and $auth_method ) {
$smtp_port = $default_smtp_tls_port unless $smtp_port;
$smtp = TLS_auth->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password, Auth_Method=>$auth_method);
if( $smtp ) {
my $message = oneline($smtp->message());
die "cannot connect with TLS/$auth_method: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $tls ) {
$smtp_port = $default_smtp_tls_port unless $smtp_port;
$smtp = Net::SMTP::TLS->new($smtp_server, Timeout=>$timeout, Port=>$smtp_port, User=>$username, Password=>$password);
if( $smtp ) {
my $message = oneline($smtp->message());
die "cannot connect with TLS: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $ssl ) {
$smtp_port = $default_smtp_ssl_port unless $smtp_port;
$smtp = Net::SMTP::SSL->new($smtp_server, Port => $smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp && $username ) {
$smtp->auth($username, $password);
my $message = oneline($smtp->message());
die "cannot connect with SSL/password: $message" if $smtp->code() =~ m/53\d/;
}
}
elsif( $auth_method ) {
$smtp_port = $default_smtp_port unless $smtp_port;
$smtp = Net::SMTP_auth->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp ) {
$smtp->auth($auth_method, $username, $password);
my $message = oneline($smtp->message());
die "cannot connect with SSL/$auth_method: $message" if $smtp->code() =~ m/53\d/;
}
}
else {
$smtp_port = $default_smtp_port unless $smtp_port;
$smtp = Net::SMTP->new($smtp_server, Port=>$smtp_port, Timeout=>$timeout,Debug=>$smtp_debug);
if( $smtp && $username ) {
$smtp->auth($username, $password);
my $message = oneline($smtp->message());
die "cannot connect with password: $message" if $smtp->code() =~ m/53\d/;
}
}
};
if( $@ ) {
$@ =~ s/\n/ /g; # the error message can be multiline but we want our output to be just one line
print "SMTP SEND CRITICAL - $@\n";
exit $status{CRITICAL};
}
unless( $smtp ) {
print "SMTP SEND CRITICAL - Could not connect to $smtp_server port $smtp_port\n";
exit $status{CRITICAL};
}
my $time_connected = time;
# add the monitored server's banner to the report
if( $tls ) {
$report->{banner} = "";
}
elsif( $ssl ) {
$report->{banner} = $smtp->banner || "";
chomp $report->{banner};
}
else {
$report->{banner} = $smtp->banner || "";
chomp $report->{banner};
}
# send email
if( $stdin ) {
$body = "";
while(<STDIN>) {
$body .= $_;
}
}
# if user wants to use template substitutions, this is the place to process body and headers
if( $template ) {
foreach my $item (@header,$body) {
my $t = Text::Template->new(TYPE=>'STRING',SOURCE=>$item,PACKAGE=>'SmtpMessageTemplate');
$item = $t->fill_in(PREPEND=>q{package SmtpMessageTemplate;});
# print "item: $item\n";
}
}
$smtp->mail($mailfrom);
foreach( @mailto ) {
# the two SMTP modules have different error reporting mechanisms:
if( $tls ) {
# Net::SMTP::TLS croaks when the recipient is rejected
eval {
$smtp->to($_);
};
if( $@ ) {
print "SMTP SEND CRITICAL - Could not send to $_\n";
print "Reason: $@\n" if $verbose;
exit $status{CRITICAL};
}
}
else {
# Net::SMTP returns false when the recipient is rejected
my $to_returned = $smtp->to($_);
if( !$to_returned ) {
print "SMTP SEND CRITICAL - Could not send to $_\n";
print "Reason: Recipient rejected or authentication failed\n" if $verbose;
exit $status{CRITICAL};
}
}
}
# Net::SMTP::TLS doesn't implement code() so we need to wrap calls in eval to get our error messages
# start data transfer (expect response 354)
$smtp->data();
# send data
$smtp->datasend("To: ".join(", ",@mailto)."\n");
$smtp->datasend("From: $mailfrom\n");
foreach( @header ) {
$smtp->datasend("$_\n");
}
$smtp->datasend("\n");
$smtp->datasend($body);
$smtp->datasend("\n");
eval {
# end data transfer (expect response 250)
$smtp->dataend();
};
if( $@ ) {
$actual_response = $tls ? get_tls_error($@) : $smtp->code();
}
else {
$actual_response = $tls ? "250" : $smtp->code(); # no error means we got 250
}
eval {
# disconnect from SMTP server (expect response 221)
$smtp->quit();
};
if( $@ ) {
push @warning, "Error while disconnecting from $smtp_server";
}
# calculate elapsed time and issue warnings
my $time_end = time;
my $elapsedtime = $time_end - $time_start;
$report->{seconds} = $elapsedtime;
push @warning, "connection time more than $warntime" if( $time_connected - $time_start > $warntime );
push @critical, "connection time more than $criticaltime" if( $time_connected - $time_start > $criticaltime );
push @critical, "response was $actual_response but expected $expect_response" if ( $actual_response ne $expect_response );
# print report and exit with known status
my $perf_data = "elapsed=".$report->{seconds}."s;$warntime;$criticaltime"; # TODO: need a component for safely generating valid perf data format. for notes on the format, see http://www.perfparse.de/tiki-view_faq.php?faqId=6 and http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN185
my $short_report = $report->text(qw/seconds/) . " | $perf_data";
my $long_report = join("", map { "$_: $report->{$_}\n" } qw/banner/ );
if( scalar @critical ) {
my $crit_alerts = join(", ", @critical);
print "SMTP SEND CRITICAL - $crit_alerts; $short_report\n";
print $long_report if $verbose;
exit $status{CRITICAL};
}
if( scalar @warning ) {
my $warn_alerts = join(", ", @warning);
print "SMTP SEND WARNING - $warn_alerts; $short_report\n";
print $long_report if $verbose;
exit $status{WARNING};
}
print "SMTP SEND OK - $short_report\n";
print $long_report if $verbose;
exit $status{OK};
# utility to load required modules. exits if unable to load one or more of the modules.
sub load_modules {
my @missing_modules = ();
foreach( @_ ) {
eval "require $_";
push @missing_modules, $_ if $@;
}
if( @missing_modules ) {
print "Missing perl modules: @missing_modules\n";
return 0;
}
return 1;
}
# utility to extract error codes out of Net::SMTP::TLS croak messages
sub get_tls_error {
my ($errormsg) = @_;
$errormsg =~ m/: (\d+) (.+)/;
my $code = $1;
return $code;
}
# looks for a specific header in a list of headers; returns true if found
sub find_header {
my ($name, @list) = @_;
return scalar grep { m/^$name: /i } @list;
}
# RFC 2822 date header
sub default_date_header {
return strftime "Date: %a, %e %b %Y %H:%M:%S %z (%Z)", gmtime;
}
# RFC 2822 message id header
sub default_messageid_header {
my $random = randomstring(16,qw/0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z/);
my $hostname = `hostname`;
chomp $hostname;
return "Message-ID: <".time.".".$random.".checksmtpsend@".$hostname.">";
}
# returns a random string of specified length using characters from specified set
sub randomstring {
my ($length,@set) = @_;
my $size = scalar @set;
my $string = "";
while($length--) {
$string .= $set[int(rand($size))];
}
return $string;
}
# replaces all newlines in the input string with spaces
sub oneline {
my ($input) = @_;
$input =~ s/[\r\n]+/ /g;
return $input;
}
# NAME
# PluginReport
# SYNOPSIS
# $report = new PluginReport;
# $report->{label1} = "value1";
# $report->{label2} = "value2";
# print $report->text(qw/label1 label2/);
package PluginReport;
sub new {
my ($proto,%p) = @_;
my $class = ref($proto) || $proto;
my $self = bless {}, $class;
$self->{$_} = $p{$_} foreach keys %p;
return $self;
}
sub text {
my ($self,@labels) = @_;
my @report = map { "$self->{$_} $_" } grep { defined $self->{$_} } @labels;
my $text = join(", ", @report);
return $text;
}
package SmtpMessageTemplate;
sub trim {
my ($text) = @_;
$text =~ s/^\s*//;
$text =~ s/\s*$//;
return $text;
}
# NAME
# TLS_auth
# SYNOPSYS
#
# Based on contribution by Brad Guillory
package TLS_auth;
#use Net::SMTP::TLS;
our @ISA = qw(Net::SMTP::TLS);
use Carp;
sub new {
my ($proto,$server,%p) = @_;
my $class = ref($proto) || $proto;
#my $self = bless {}, $class;
no strict 'refs';
no warnings 'once';
*Net::SMTP::TLS::login = *TLS_auth::login; # override parent's login with ours so when it's called in the constructor, our overriden version will be used
my $self = Net::SMTP::TLS->new($server,%p);
return $self;
}
sub login {
my ($self) = @_;
my $type = $self->{features}->{AUTH};
if(not $type){
die "Server did not return AUTH in capabilities\n"; # croak
}
# print "Feature: $type\nAuth Method: $self->{Auth_Method}\n";
if($type =~ /CRAM\-MD5/ and $self->{Auth_Method} =~ /CRAM\-MD5/i){
$self->auth_MD5();
}elsif($type =~ /LOGIN/ and $self->{Auth_Method} =~ /LOGIN/i){
$self->auth_LOGIN();
}elsif($type =~ /PLAIN/ and $self->{Auth_Method} =~ /PLAIN/i){
#print "Calling auth_PLAIN\n";
$self->auth_PLAIN();
}else{
die "Unsupported Authentication mechanism: $self->{Auth_Method}\n"; # croak
}
}
package main;
1;

View File

@ -0,0 +1,69 @@
HOW TO CONNECT TO IMAP SERVER MANUALLY
This how-to borrowed from: http://www.bincimap.org/bincimap-faq.html
1) Connection
Using telnet, connect to your service on port 143. Replace "server" with your server's name. If the server is set up correctly, you will see this greeting:
# telnet server 143
* OK IMAP Server ready
If you have SSL enabled (most likely you do), connect to port 993 with the openssl tool. If the server is set up correctly, you will see this greeting:
# openssl s_client -connect server:993 -crlf
* OK IMAP Server ready
2) Logging in / authenticating
Firstly, check your bincimap.conf file, in the "Authentication" section, for this setting:
allow plain auth in non ssl = "no"
If you want users to be able to connect without using SSL, set this to "yes".
Using either the telnet (in case of "yes" in the above example) or openssl tool, try the LOGIN command, replacing "username" with one username on your server, and "password" with that user's password. You should get the reply on the second line.
1 LOGIN username password
1 LOGIN completed
Note that you should try logging in with at least two users to check that this feature is working properly.
3) Listing, creating, renaming and deleting mailboxes
Enter the following command to list the user's first level mailboxes. You should get at least one line of response (starting with "* LIST") before you get the "2 OK LIST" reponse.
2 LIST "" "%"
* LIST (\UnMarked) "/" "INBOX"
2 OK LIST completed
Check your bincimap.conf file, under the Mailbox section, and check the "depot" setting. Try creating a mailbox with the following command, replacing mailbox with a name of your choice. Note that if you are using the Maildir++ depot setting, you must use "INBOX/mailbox" instead:
3 CREATE mailbox
3 OK CREATE completed
Rename the mailbox with this command. Note the "INBOX/" prefix when using a Maildir++ depot. (After that, rerunning the LIST command from above will give you a slightly different result than before):
4 RENAME mailbox newmailbox
4 OK RENAME completed
Now delete the mailbox with this command:
5 DELETE newmailbox
5 OK DELETE completed
4) Selecting a mailbox and looking inside
Select your INBOX with this command. Note that the response may be slightly different from in this example:
6 SELECT INBOX
* 146 EXISTS
* OK [UIDVALIDITY 1047992537]
* OK [UIDNEXT 2683] 2683 is the next UID
* FLAGS (\Answered \Flagged \Deleted \Recent \Seen \Draft)
* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft)] Limited
6 OK [READ-WRITE]
Fetch the flags of all your messages with this command. Note that the "..." is for editorial clarity, many lines of output have been omitted in this example:
7 FETCH 1:* FLAGS
* 1 FETCH (FLAGS (\Seen \Answered))
* 2 FETCH (FLAGS (\Seen \Answered))
...
* 146 FETCH (FLAGS (\Seen \Answered))
7 OK FETCH completed
Set a flag with this command:
8 STORE 1 +FLAGS \Flagged
* FETCH (FLAGS (\Seen \Flagged))
8 OK STORE completed
5) Logging out
9 LOGOUT
* BYE Server logging out
9 OK LOGOUT finished.

View File

@ -0,0 +1,15 @@
HOW TO TEST THE PLUGIN
Run the shell script tests which start the test server automatically:
./test/3_email_delivery.sh
If you want to start up the test server yourself:
sudo perl test/dummy_smtp_server.pl

View File

@ -0,0 +1,522 @@
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>check_email_delivery - sends email and verifies delivery</title>
<link rel="stylesheet" href="plainwhite.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:jonathan@greek.local" />
</head>
<body>
<!-- INDEX BEGIN -->
<div name="index">
<p><a name="__index__"></a></p>
<!--
<ul>
<li><a href="#name">NAME</a></li>
<li><a href="#synopsis">SYNOPSIS</a></li>
<li><a href="#options">OPTIONS</a></li>
<li><a href="#examples">EXAMPLES</a></li>
<ul>
<li><a href="#send_a_message_with_custom_headers">Send a message with custom headers</a></li>
<li><a href="#set_warning_and_critical_timeouts_for_receive_plugin_only_">Set warning and critical timeouts for receive plugin only:</a></li>
</ul>
<li><a href="#exit_codes">EXIT CODES</a></li>
<li><a href="#nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></li>
<li><a href="#changes">CHANGES</a></li>
<li><a href="#author">AUTHOR</a></li>
<li><a href="#copyright_and_license">COPYRIGHT AND LICENSE</a></li>
</ul>
-->
</div>
<!-- INDEX END -->
<p>
</p>
<hr />
<h1><a name="name">NAME</a></h1>
<p>check_email_delivery - sends email and verifies delivery</p>
<p>
</p>
<hr />
<h1><a name="synopsis">SYNOPSIS</a></h1>
<pre>
check_email_delivery -vV
check_email_delivery --usage
check_email_delivery --help</pre>
<p>
</p>
<hr />
<h1><a name="options">OPTIONS</a></h1>
<dl>
<dt><strong><a name="warning_seconds_smtp_seconds_imap_seconds" class="item">--warning &lt;seconds&gt;[,&lt;smtp_seconds&gt;,&lt;imap_seconds&gt;]</a></strong></dt>
<dd>
<p>Exit with WARNING if the most recent email found is older than &lt;seconds&gt;. The
optional &lt;smtp_seconds&gt; and &lt;imap_seconds&gt; parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -w &lt;seconds&gt;[,&lt;send&gt;[,&lt;recv&gt;]]</p>
<p>When using the --plugin option, only one parameter is supported (-w &lt;seconds&gt;) and it will apply
to the entire process. You can specify a warning threshold specific to each plugin in the
plugin command line.</p>
<p>When using the --plugin option, no measuring of &quot;most recent email&quot; is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.</p>
</dd>
<dt><strong><a name="critical_seconds_smtp_seconds_imap_seconds" class="item">--critical &lt;seconds&gt;[,&lt;smtp_seconds&gt;,&lt;imap_seconds&gt;]</a></strong></dt>
<dd>
<p>Exit with CRITICAL if the most recent email found is older than &lt;seconds&gt;. The
optional &lt;smtp_seconds&gt; and &lt;imap_seconds&gt; parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -c &lt;seconds&gt;[,&lt;send&gt;[,&lt;recv&gt;]]</p>
<p>When using the --plugin option, only one parameter is supported (-c &lt;seconds&gt;) and it will apply
to the entire process. You can specify a critical threshold specific to each plugin in the
plugin command line.</p>
<p>When using the --plugin option, no measuring of &quot;most recent email&quot; is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.</p>
</dd>
<dt><strong><a name="timeout_seconds" class="item">--timeout &lt;seconds&gt;</a></strong></dt>
<dt><strong><a name="timeout_smtp_seconds_imap_seconds" class="item">--timeout &lt;smtp_seconds&gt;,&lt;imap_seconds&gt;</a></strong></dt>
<dt><strong><a name="timeout_plugin1_seconds_plugin2_seconds" class="item">--timeout &lt;plugin1_seconds&gt;,&lt;plugin2_seconds&gt;,...</a></strong></dt>
<dd>
<p>Exit with CRITICAL if the plugins do not return a status within the specified number of seconds.
When only one parameter is used, it applies to each plugin. When multiple parameters are used
(separated by commas) they apply to plugins in the same order the plugins were specified on the
command line. When using --timeout but not the --plugin option, the first parameter is for
check_smtp_send and the second is for check_imap_receive.</p>
</dd>
<dt><strong><a name="alert_pluginn" class="item">--alert &lt;pluginN&gt;</a></strong></dt>
<dd>
<p>Exit with WARNING or CRITICAL only if a warning or error (--warning, --critical, or --timeout)
occurs for specified plugins. If a warning or error occurs for non-specified plugins that run
BEFORE the specified plugins, the exit status will be UNKNOWN. If a warning of error occurs
for non-specified plugins that run AFTER the specified plugins, the exit status will not be
affected.</p>
<p>You would use this option if you are using check_email_delivery with the --plugin option and
the plugins you configure each use different servers, for example different SMTP and IMAP servers.
By default, if you do not use the --alert option, if anything goes wrong during the email delivery
check, a WARNING or CRITICAL alert will be issued. This means that if you define check_email_delivery
for the SMTP server only and the IMAP server fails, Nagios will alert you for the SMTP server which
would be misleading. If you define it for both the SMTP server and IMAP server and just one of them
fails, Nagios will alert you for both servers, which would still be misleading. If you have this
situation, you may want to use the --alert option. You define the check_email_delivery check for
both servers: for the SMTP server (first plugin) you use --alert 1, and for for the IMAP server
(second plugin) you use --alert 2. When check_email_delivery runs with --alert 1 and the SMTP
server fails, you will get the appropriate alert. If the IMAP server fails it will not affect the
status. When check_email_delivery runs with --alert 2 and the SMTP server fails, you will get the
UNKNOWN return code. If the IMAP server generates an alert you will get a WARNING or CRITICAL as
appropriate.</p>
<p>You can repeat this option to specify multiple plugins that should cause an alert.
Do this if you have multiple plugins on the command line but some of them involve the same server.</p>
<p>See also: --plugin.
Also known as: -A &lt;pluginN&gt;</p>
</dd>
<dt><strong><a name="wait_seconds_seconds" class="item">--wait &lt;seconds&gt;[,&lt;seconds&gt;,...]</a></strong></dt>
<dd>
<p>How long to wait between sending the message and checking that it was received. View default with
the -vV option.</p>
<p>When using the --plugin option, you can specify as many wait-between times as you have plugins
(minus the last plugin, because it makes no sense to wait after running the last one). For
example, if you use the --plugin option twice to specify an SMTP plugin and an IMAP plugin, and
you want to wait 5 seconds between sending and receiving, then you would specify --wait 5. A second
example, if you are using the --plugin option three times, then specifying -w 5 will wait 5 seconds
between the second and third plugins also. You can specify a different wait time
of 10 seconds between the second and third plugins, like this: -w 5,10.</p>
</dd>
<dt><strong><a name="hostname_server" class="item">--hostname &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the SMTP and IMAP server. Examples: mail.server.com, localhost, 192.168.1.100.
Also known as: -H &lt;server&gt;</p>
</dd>
<dt><strong><a name="smtp_server_server" class="item">--smtp-server &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the SMTP server. Examples: smtp.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.</p>
</dd>
<dt><strong><a name="smtp_port_number" class="item">--smtp-port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the SMTP server. Default is 25.</p>
</dd>
<dt><strong><a name="smtp_username_username" class="item">--smtp-username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="smtp_password_password" class="item">--smtp-password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to the SMTP server with the TLS option.
Use these options if the SMTP account has a different username/password than the
IMAP account you are testing. These options take precendence over the --username and
the --password options.</p>
<p>These are shell-escaped; special characters are ok.</p>
</dd>
<dt><strong><a name="imap_server_server" class="item">--imap-server &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the IMAP server. Examples: imap.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.</p>
</dd>
<dt><strong><a name="imap_port_number" class="item">--imap-port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the IMAP server. Default is 143. If you use SSL the default is 993.</p>
</dd>
<dt><strong><a name="imap_username_username" class="item">--imap-username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="imap_password_password" class="item">--imap-password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to the IMAP server.
Use these options if the IMAP account has a different username/password than the
SMTP account you are testing. These options take precendence over the --username and
the --password options.</p>
<p>These are shell-escaped; special characters are ok.</p>
</dd>
<dt><strong><a name="username_username" class="item">--username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="password_password" class="item">--password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to IMAP server.
Also known as: -U &lt;username&gt; -P &lt;password&gt;</p>
<p>Also used as the username and password for SMTP when the TLS option is enabled.
To specify a separate set of credentials for SMTP authentication, see the
options --smtp-username and --smtp-password.</p>
</dd>
<dt><strong><a name="imap_check_interval_seconds" class="item">--imap-check-interval &lt;seconds&gt;</a></strong></dt>
<dd>
<p>How long to wait between polls of the imap-server for the specified mail. Default is 5 seconds.</p>
</dd>
<dt><strong><a name="imap_retries_times" class="item">--imap-retries &lt;times&gt;</a></strong></dt>
<dd>
<p>How many times to poll the imap-server for the mail, before we give up. Default is 10.</p>
</dd>
<dt><strong><a name="body_message" class="item">--body &lt;message&gt;</a></strong></dt>
<dd>
<p>Use this option to specify the body of the email message.</p>
</dd>
<dt><strong><a name="header_header" class="item">--header &lt;header&gt;</a></strong></dt>
<dd>
<p>Use this option to set an arbitrary header in the message. You can use it multiple times.</p>
</dd>
<dt><strong><a name="mailto_recipient_your_net" class="item">--mailto <a href="mailto:recipient@your.net">recipient@your.net</a></a></strong></dt>
<dd>
<p>You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):</p>
<p>$ check_email_delivery ... --mailto <a href="mailto:recipient@your.net,recipient2@your.net">recipient@your.net,recipient2@your.net</a> --mailfrom <a href="mailto:sender@your.net">sender@your.net</a></p>
<p>This argument is shell-escaped; special characters or angle brackets around the address are ok.</p>
</dd>
<dt><strong><a name="mailfrom_sender_your_net" class="item">--mailfrom <a href="mailto:sender@your.net">sender@your.net</a></a></strong></dt>
<dd>
<p>Use this option to set the &quot;from&quot; address in the email.</p>
</dd>
<dt><strong><a name="imapssl_item_noimapssl" class="item">--imapssl
=item --noimapssl</a></strong></dt>
<dd>
<p>Use this to enable or disable SSL for the IMAP plugin.</p>
<p>This argument is shell-escaped; special characters or angle brackets around the address are ok.</p>
</dd>
<dt><strong><a name="smtptls_item_nosmtptls" class="item">--smtptls
=item --nosmtptls</a></strong></dt>
<dd>
<p>Use this to enable or disable TLS/AUTH for the SMTP plugin.</p>
</dd>
<dt><strong><a name="libexec" class="item">--libexec</a></strong></dt>
<dd>
<p>Use this option to set the path of the Nagios libexec directory. The default is
/usr/local/nagios/libexec. This is where this plugin looks for the SMTP and IMAP
plugins that it depends on.</p>
</dd>
<dt><strong><a name="plugin_command" class="item">--plugin &lt;command&gt;</a></strong></dt>
<dd>
<p>This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It frees the plugin from depending on specific external plugins and generalizes the
work done to determine that the email loop is operational. When using the --plugin
option, the following options are ignored: libexec, imapssl, smtptls, hostname,
username, password, smtp*, imap*, mailto, mailfrom, body, header, search.</p>
<p>Use this option multiple times to specify the complete trip. Typically, you would use
this twice to specify plugins for SMTP and IMAP, or SMTP and POP3.</p>
<p>The output will be success if all the plugins return success. Each plugin should be a
standard Nagios plugin.</p>
<p>A random token will be automatically generated and passed to each plugin specified on
the command line by substituting the string %TOKEN1%.</p>
<p>Example usage:</p>
<pre>
command_name check_email_delivery
command_line check_email_delivery
--plugin &quot;$USER1$/check_smtp_send -H $ARG1$ --mailto recipient@your.net --mailfrom sender@your.net --header 'Subject: Nagios Test %TOKEN1%.'&quot;
--plugin &quot;$USER1$/check_imap_receive -H $ARG1$ -U $ARG1$ -P $ARG2$ -s SUBJECT -s 'Nagios Test %TOKEN1%.'&quot;</pre>
<p>This technique allows for a lot of flexibility in configuring the plugins that test
each part of your email delivery loop.</p>
<p>See also: --token.
Also known as: -p &lt;command&gt;</p>
</dd>
<dt><strong><a name="token_format" class="item">--token &lt;format&gt;</a></strong></dt>
<dd>
<p>This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It can be used in conjunction with --plugin to control the tokens that are generated
and passed to the plugins, like %TOKEN1%.</p>
<p>Use this option multiple times to specify formats for different tokens. For example,
if you want %TOKEN1% to consist of only alphabetical characters but want %TOKEN2% to
consist of only digits, then you might use these options: --token aaaaaa --token nnnnn</p>
<p>Any tokens used in your plugin commands that have not been specified by --token &lt;format&gt;
will default to --token U-X-Y</p>
<p>Token formats:
a - alpha character (a-z)
n - numeric character (0-9)
c - alphanumeric character (a-z0-9)
h - hexadecimal character (0-9a-f)
U - unix time, seconds from epoch. eg 1193012441
X - a word from the pgp even list. eg aardvark
Y - a word from the pgp odd list. eg adroitness</p>
<p>Caution: It has been observed that some IMAP servers do not handle underscores well in the
search criteria. For best results, avoid using underscores in your tokens. Use hyphens or commas instead.</p>
<p>See also: --plugin.
Also known as: -T &lt;format&gt;</p>
<p>The PGP word list was obtained from <a href="http://en.wikipedia.org/wiki/PGP_word_list">http://en.wikipedia.org/wiki/PGP_word_list</a></p>
</dd>
<dt><strong><a name="file_file" class="item">--file &lt;file&gt;</a></strong></dt>
<dd>
<p>Save (append) status information into the given tab-delimited file. Format used:</p>
<pre>
token start-time end-time status plugin-num output</pre>
<p>Note: format may change in future versions and may become configurable.</p>
<p>This option available as of version 0.6.2.</p>
<p>Also known as: -F &lt;file&gt;</p>
</dd>
<dt><strong><a name="hires" class="item">--hires</a></strong></dt>
<dd>
<p>Use the Time::HiRes module to measure time, if available.</p>
</dd>
<dt><strong><a name="verbose" class="item">--verbose</a></strong></dt>
<dd>
<p>Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
Also known as: -v</p>
</dd>
<dt><strong><a name="version" class="item">--version</a></strong></dt>
<dd>
<p>Display plugin version and exit.
Also known as: -V</p>
</dd>
<dt><strong><a name="help" class="item">--help</a></strong></dt>
<dd>
<p>Display this documentation and exit. Does not work in the ePN version.
Also known as: -h</p>
</dd>
<dt><strong><a name="usage" class="item">--usage</a></strong></dt>
<dd>
<p>Display a short usage instruction and exit.</p>
</dd>
</dl>
<p>
</p>
<hr />
<h1><a name="examples">EXAMPLES</a></h1>
<p>
</p>
<h2><a name="send_a_message_with_custom_headers">Send a message with custom headers</a></h2>
<p>$ check_email_delivery -H mail.server.net --mailto <a href="mailto:recipient@your.net">recipient@your.net</a> --mailfrom <a href="mailto:sender@your.net">sender@your.net</a>
--username recipient --password secret</p>
<p>EMAIL DELIVERY OK - 1 seconds</p>
<p>
</p>
<h2><a name="set_warning_and_critical_timeouts_for_receive_plugin_only_">Set warning and critical timeouts for receive plugin only:</a></h2>
<p>$ check_email_delivery -H mail.server.net --mailto <a href="mailto:recipient@your.net">recipient@your.net</a> --mailfrom <a href="mailto:sender@your.net">sender@your.net</a>
--username recipient --password secret -w ,,5 -c ,,15</p>
<p>EMAIL DELIVERY OK - 1 seconds</p>
<p>
</p>
<hr />
<h1><a name="exit_codes">EXIT CODES</a></h1>
<p><table cellspacing="0" cellpadding="0"><tr><td>Complies with the Nagios plug-in specification:
<tr><td> 0<td>OK<td>The plugin was able to check the service and it appeared to be functioning properly
<tr><td> 1<td>Warning<td>The plugin was able to check the service, but it appeared to be above some &quot;warning&quot; threshold or did not appear to be working properly
<tr><td> 2<td>Critical<td>The plugin detected that either the service was not running or it was above some &quot;critical&quot; threshold
<tr><td> 3<td>Unknown<td>Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service</table></p>
<p>
</p>
<hr />
<h1><a name="nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></h1>
<p>Nagios plugin reference: <a href="http://nagiosplug.sourceforge.net/developer-guidelines.html">http://nagiosplug.sourceforge.net/developer-guidelines.html</a></p>
<p>This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.</p>
<p>Other than that, it attempts to follow published guidelines for Nagios plugins.</p>
<p>
</p>
<hr />
<h1><a name="changes">CHANGES</a></h1>
<pre>
Wed Oct 29 13:08:00 PST 2005
+ version 0.1</pre>
<pre>
Wed Nov 9 17:16:09 PST 2005
+ updated arguments to check_smtp_send and check_imap_receive
+ added eval/alarm block to implement -c option
+ added wait option to adjust sleep time between smtp and imap calls
+ added delay-warn and delay-crit options to adjust email delivery warning thresholds
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2</pre>
<pre>
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson &lt;johann (at) axis.com&gt;)
+ version 0.2.1
+ corrected bug in getoptions ($imap_server would never ever be set from command-line...)
+ will not make $smtp_server and $imap_server == $host if they're defined on commandline
+ added support for multiple polls of imap-server, with specified intervals
+ changed default behaviour in check_imap_server (searches for the specific id in subject and deletes mails found)
+ increased default delay_warn from 65 seconds to 95 seconds</pre>
<pre>
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton &lt;geoff.crompton@strategicdata.com.au&gt;)
+ fixed a bug in getoptions
+ version 0.2.2</pre>
<pre>
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ version 0.2.3</pre>
<pre>
Fri Apr 27 20:32:53 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ changed connection error to display timeout only if timeout was the error
+ default IMAP plugin is libexec/check_imap_receive (also checking for same but with .pl extension)
+ default SMTP plugin is libexec/check_smtp_send (also checking for same but with .pl extension)
+ removed default values for SMTP port and IMAP port to allow those plugins to set the defaults; so current behavior stays the same and will continue to make sense with SSL
+ version 0.3</pre>
<pre>
Thu Oct 11 10:00:00 EET 2007 (by Timo Virtaneva &lt;timo (at) virtaneva dot com&gt;
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.3.1</pre>
<pre>
Sun Oct 21 11:01:03 PDT 2007
+ added support for TLS options to the SMTP plugin
+ version 0.4</pre>
<pre>
Sun Oct 21 16:17:14 PDT 2007
+ added support for arbitrary plugins to send and receive mail (or anthing else!). see the --plugin option.
+ version 0.5</pre>
<pre>
Tue Dec 4 07:36:20 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ shortcut option for --token is now -T to avoid clash with standard shortcut -t for --timeout
+ fixed some minor pod formatting issues for perldoc
+ version 0.5.1</pre>
<pre>
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.5.2</pre>
<pre>
Thu Jan 17 20:27:36 PST 2008 (by Timo Virtaneva &lt;timo (at) virtaneva dot com&gt; on Thu Oct 11 10:00:00 EET 2007)
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.5.3</pre>
<pre>
Mon Jan 28 22:11:02 PST 2008
+ fixed a bug, smtp-password and imap-password are now string parameters
+ added --alert option to allow selection of which plugin(s) should cause a WARNING or CRITICAL alert
+ version 0.6</pre>
<pre>
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable &quot;%status&quot; will not stay shared in load_modules
+ version 0.6.1</pre>
<pre>
Mon May 26 10:39:19 PDT 2008
+ added --file option to allow plugin to record status information into a tab-delimited file
+ changed default token from U_X_Y to U-X-Y
+ version 0.6.2</pre>
<pre>
Wed Jan 14 08:29:35 PST 2009
+ fixed a bug that the --header parameter was not being passed to the smtp plugin.
+ version 0.6.3</pre>
<pre>
Mon Jun 8 15:43:48 PDT 2009
+ added performance data for use with PNP4Nagios! (thanks to Ben Ritcey for the patch)
+ version 0.6.4</pre>
<pre>
Wed Sep 16 07:10:10 PDT 2009
+ added elapsed time in seconds to performance data
+ version 0.6.5</pre>
<pre>
Fri Oct 8 19:48:44 PDT 2010
+ fixed uniform IMAP and SMTP username and password bug (thanks to Micle Moerenhout for pointing it out)
+ version 0.6.6</pre>
<pre>
Mon Jan 3 08:24:23 PST 2011
+ added shell escaping for smtp-username, smtp-password, mailto, mailfrom, imap-username, and imap-password arguments
+ version 0.7.0</pre>
<pre>
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1</pre>
<pre>
Sun Jun 12 17:17:06 AST 2011
+ added --imap-mailbox option to pass through to check_imap_receive --mailbox option
+ added --ssl option to conveniently enable both --smtp-tls and --imap-ssl
+ version 0.7.2</pre>
<p>
</p>
<hr />
<h1><a name="author">AUTHOR</a></h1>
<p>Jonathan Buhacoff &lt;<a href="mailto:jonathan@buhacoff.net">jonathan@buhacoff.net</a>&gt;</p>
<p>
</p>
<hr />
<h1><a name="copyright_and_license">COPYRIGHT AND LICENSE</a></h1>
<pre>
Copyright (C) 2005-2011 Jonathan Buhacoff</pre>
<pre>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.</pre>
<pre>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.</pre>
<pre>
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;<a href="http://www.gnu.org/licenses/&gt">http://www.gnu.org/licenses/&gt</a>;.</pre>
<pre>
<a href="http://www.gnu.org/licenses/gpl.txt">http://www.gnu.org/licenses/gpl.txt</a></pre>
</body>
</html>

View File

@ -0,0 +1,472 @@
=pod
=head1 NAME
check_email_delivery - sends email and verifies delivery
=head1 SYNOPSIS
check_email_delivery -vV
check_email_delivery --usage
check_email_delivery --help
=head1 OPTIONS
=over
=item --warning <seconds>[,<smtp_seconds>,<imap_seconds>]
Exit with WARNING if the most recent email found is older than <seconds>. The
optional <smtp_seconds> and <imap_seconds> parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -w <seconds>[,<send>[,<recv>]]
When using the --plugin option, only one parameter is supported (-w <seconds>) and it will apply
to the entire process. You can specify a warning threshold specific to each plugin in the
plugin command line.
When using the --plugin option, no measuring of "most recent email" is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.
=item --critical <seconds>[,<smtp_seconds>,<imap_seconds>]
Exit with CRITICAL if the most recent email found is older than <seconds>. The
optional <smtp_seconds> and <imap_seconds> parameters will be passed on to the
included plugins that are used for those tasks. If they are not
given then they will not be passed on and the default for that plugin will apply.
Also known as: -c <seconds>[,<send>[,<recv>]]
When using the --plugin option, only one parameter is supported (-c <seconds>) and it will apply
to the entire process. You can specify a critical threshold specific to each plugin in the
plugin command line.
When using the --plugin option, no measuring of "most recent email" is done because we would
not know how to read this information from receive plugins. This may be addressed in future versions.
=item --timeout <seconds>
=item --timeout <smtp_seconds>,<imap_seconds>
=item --timeout <plugin1_seconds>,<plugin2_seconds>,...
Exit with CRITICAL if the plugins do not return a status within the specified number of seconds.
When only one parameter is used, it applies to each plugin. When multiple parameters are used
(separated by commas) they apply to plugins in the same order the plugins were specified on the
command line. When using --timeout but not the --plugin option, the first parameter is for
check_smtp_send and the second is for check_imap_receive.
=item --alert <pluginN>
Exit with WARNING or CRITICAL only if a warning or error (--warning, --critical, or --timeout)
occurs for specified plugins. If a warning or error occurs for non-specified plugins that run
BEFORE the specified plugins, the exit status will be UNKNOWN. If a warning of error occurs
for non-specified plugins that run AFTER the specified plugins, the exit status will not be
affected.
You would use this option if you are using check_email_delivery with the --plugin option and
the plugins you configure each use different servers, for example different SMTP and IMAP servers.
By default, if you do not use the --alert option, if anything goes wrong during the email delivery
check, a WARNING or CRITICAL alert will be issued. This means that if you define check_email_delivery
for the SMTP server only and the IMAP server fails, Nagios will alert you for the SMTP server which
would be misleading. If you define it for both the SMTP server and IMAP server and just one of them
fails, Nagios will alert you for both servers, which would still be misleading. If you have this
situation, you may want to use the --alert option. You define the check_email_delivery check for
both servers: for the SMTP server (first plugin) you use --alert 1, and for for the IMAP server
(second plugin) you use --alert 2. When check_email_delivery runs with --alert 1 and the SMTP
server fails, you will get the appropriate alert. If the IMAP server fails it will not affect the
status. When check_email_delivery runs with --alert 2 and the SMTP server fails, you will get the
UNKNOWN return code. If the IMAP server generates an alert you will get a WARNING or CRITICAL as
appropriate.
You can repeat this option to specify multiple plugins that should cause an alert.
Do this if you have multiple plugins on the command line but some of them involve the same server.
See also: --plugin.
Also known as: -A <pluginN>
=item --wait <seconds>[,<seconds>,...]
How long to wait between sending the message and checking that it was received. View default with
the -vV option.
When using the --plugin option, you can specify as many wait-between times as you have plugins
(minus the last plugin, because it makes no sense to wait after running the last one). For
example, if you use the --plugin option twice to specify an SMTP plugin and an IMAP plugin, and
you want to wait 5 seconds between sending and receiving, then you would specify --wait 5. A second
example, if you are using the --plugin option three times, then specifying -w 5 will wait 5 seconds
between the second and third plugins also. You can specify a different wait time
of 10 seconds between the second and third plugins, like this: -w 5,10.
=item --hostname <server>
Address or name of the SMTP and IMAP server. Examples: mail.server.com, localhost, 192.168.1.100.
Also known as: -H <server>
=item --smtp-server <server>
Address or name of the SMTP server. Examples: smtp.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.
=item --smtp-port <number>
Service port on the SMTP server. Default is 25.
=item --smtp-username <username>
=item --smtp-password <password>
Username and password to use when connecting to the SMTP server with the TLS option.
Use these options if the SMTP account has a different username/password than the
IMAP account you are testing. These options take precendence over the --username and
the --password options.
These are shell-escaped; special characters are ok.
=item --imap-server <server>
Address or name of the IMAP server. Examples: imap.server.com, localhost, 192.168.1.100.
Using this option overrides the hostname option.
=item --imap-port <number>
Service port on the IMAP server. Default is 143. If you use SSL the default is 993.
=item --imap-username <username>
=item --imap-password <password>
Username and password to use when connecting to the IMAP server.
Use these options if the IMAP account has a different username/password than the
SMTP account you are testing. These options take precendence over the --username and
the --password options.
These are shell-escaped; special characters are ok.
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
Also used as the username and password for SMTP when the TLS option is enabled.
To specify a separate set of credentials for SMTP authentication, see the
options --smtp-username and --smtp-password.
=item --imap-check-interval <seconds>
How long to wait between polls of the imap-server for the specified mail. Default is 5 seconds.
=item --imap-retries <times>
How many times to poll the imap-server for the mail, before we give up. Default is 10.
=item --body <message>
Use this option to specify the body of the email message.
=item --header <header>
Use this option to set an arbitrary header in the message. You can use it multiple times.
=item --mailto recipient@your.net
You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):
$ check_email_delivery ... --mailto recipient@your.net,recipient2@your.net --mailfrom sender@your.net
This argument is shell-escaped; special characters or angle brackets around the address are ok.
=item --mailfrom sender@your.net
Use this option to set the "from" address in the email.
=item --imapssl
=item --noimapssl
Use this to enable or disable SSL for the IMAP plugin.
This argument is shell-escaped; special characters or angle brackets around the address are ok.
=item --smtptls
=item --nosmtptls
Use this to enable or disable TLS/AUTH for the SMTP plugin.
=item --libexec
Use this option to set the path of the Nagios libexec directory. The default is
/usr/local/nagios/libexec. This is where this plugin looks for the SMTP and IMAP
plugins that it depends on.
=item --plugin <command>
This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It frees the plugin from depending on specific external plugins and generalizes the
work done to determine that the email loop is operational. When using the --plugin
option, the following options are ignored: libexec, imapssl, smtptls, hostname,
username, password, smtp*, imap*, mailto, mailfrom, body, header, search.
Use this option multiple times to specify the complete trip. Typically, you would use
this twice to specify plugins for SMTP and IMAP, or SMTP and POP3.
The output will be success if all the plugins return success. Each plugin should be a
standard Nagios plugin.
A random token will be automatically generated and passed to each plugin specified on
the command line by substituting the string %TOKEN1%.
Example usage:
command_name check_email_delivery
command_line check_email_delivery
--plugin "$USER1$/check_smtp_send -H $ARG1$ --mailto recipient@your.net --mailfrom sender@your.net --header 'Subject: Nagios Test %TOKEN1%.'"
--plugin "$USER1$/check_imap_receive -H $ARG1$ -U $ARG1$ -P $ARG2$ -s SUBJECT -s 'Nagios Test %TOKEN1%.'"
This technique allows for a lot of flexibility in configuring the plugins that test
each part of your email delivery loop.
See also: --token.
Also known as: -p <command>
=item --token <format>
This is a new option introduced in version 0.5 of the check_email_delivery plugin.
It can be used in conjunction with --plugin to control the tokens that are generated
and passed to the plugins, like %TOKEN1%.
Use this option multiple times to specify formats for different tokens. For example,
if you want %TOKEN1% to consist of only alphabetical characters but want %TOKEN2% to
consist of only digits, then you might use these options: --token aaaaaa --token nnnnn
Any tokens used in your plugin commands that have not been specified by --token <format>
will default to --token U-X-Y
Token formats:
a - alpha character (a-z)
n - numeric character (0-9)
c - alphanumeric character (a-z0-9)
h - hexadecimal character (0-9a-f)
U - unix time, seconds from epoch. eg 1193012441
X - a word from the pgp even list. eg aardvark
Y - a word from the pgp odd list. eg adroitness
Caution: It has been observed that some IMAP servers do not handle underscores well in the
search criteria. For best results, avoid using underscores in your tokens. Use hyphens or commas instead.
See also: --plugin.
Also known as: -T <format>
The PGP word list was obtained from http://en.wikipedia.org/wiki/PGP_word_list
=item --file <file>
Save (append) status information into the given tab-delimited file. Format used:
token start-time end-time status plugin-num output
Note: format may change in future versions and may become configurable.
This option available as of version 0.6.2.
Also known as: -F <file>
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Send a message with custom headers
$ check_email_delivery -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--username recipient --password secret
EMAIL DELIVERY OK - 1 seconds
=head2 Set warning and critical timeouts for receive plugin only:
$ check_email_delivery -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--username recipient --password secret -w ,,5 -c ,,15
EMAIL DELIVERY OK - 1 seconds
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 CHANGES
Wed Oct 29 13:08:00 PST 2005
+ version 0.1
Wed Nov 9 17:16:09 PST 2005
+ updated arguments to check_smtp_send and check_imap_receive
+ added eval/alarm block to implement -c option
+ added wait option to adjust sleep time between smtp and imap calls
+ added delay-warn and delay-crit options to adjust email delivery warning thresholds
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson <johann (at) axis.com>)
+ version 0.2.1
+ corrected bug in getoptions ($imap_server would never ever be set from command-line...)
+ will not make $smtp_server and $imap_server == $host if they're defined on commandline
+ added support for multiple polls of imap-server, with specified intervals
+ changed default behaviour in check_imap_server (searches for the specific id in subject and deletes mails found)
+ increased default delay_warn from 65 seconds to 95 seconds
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton <geoff.crompton@strategicdata.com.au>)
+ fixed a bug in getoptions
+ version 0.2.2
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ version 0.2.3
Fri Apr 27 20:32:53 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ changed connection error to display timeout only if timeout was the error
+ default IMAP plugin is libexec/check_imap_receive (also checking for same but with .pl extension)
+ default SMTP plugin is libexec/check_smtp_send (also checking for same but with .pl extension)
+ removed default values for SMTP port and IMAP port to allow those plugins to set the defaults; so current behavior stays the same and will continue to make sense with SSL
+ version 0.3
Thu Oct 11 10:00:00 EET 2007 (by Timo Virtaneva <timo (at) virtaneva dot com>
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.3.1
Sun Oct 21 11:01:03 PDT 2007
+ added support for TLS options to the SMTP plugin
+ version 0.4
Sun Oct 21 16:17:14 PDT 2007
+ added support for arbitrary plugins to send and receive mail (or anthing else!). see the --plugin option.
+ version 0.5
Tue Dec 4 07:36:20 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ shortcut option for --token is now -T to avoid clash with standard shortcut -t for --timeout
+ fixed some minor pod formatting issues for perldoc
+ version 0.5.1
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.5.2
Thu Jan 17 20:27:36 PST 2008 (by Timo Virtaneva <timo (at) virtaneva dot com> on Thu Oct 11 10:00:00 EET 2007)
+ Changed the header and the search criteria so that the same email-box can be used for all smtp-servers
+ version 0.5.3
Mon Jan 28 22:11:02 PST 2008
+ fixed a bug, smtp-password and imap-password are now string parameters
+ added --alert option to allow selection of which plugin(s) should cause a WARNING or CRITICAL alert
+ version 0.6
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.6.1
Mon May 26 10:39:19 PDT 2008
+ added --file option to allow plugin to record status information into a tab-delimited file
+ changed default token from U_X_Y to U-X-Y
+ version 0.6.2
Wed Jan 14 08:29:35 PST 2009
+ fixed a bug that the --header parameter was not being passed to the smtp plugin.
+ version 0.6.3
Mon Jun 8 15:43:48 PDT 2009
+ added performance data for use with PNP4Nagios! (thanks to Ben Ritcey for the patch)
+ version 0.6.4
Wed Sep 16 07:10:10 PDT 2009
+ added elapsed time in seconds to performance data
+ version 0.6.5
Fri Oct 8 19:48:44 PDT 2010
+ fixed uniform IMAP and SMTP username and password bug (thanks to Micle Moerenhout for pointing it out)
+ version 0.6.6
Mon Jan 3 08:24:23 PST 2011
+ added shell escaping for smtp-username, smtp-password, mailto, mailfrom, imap-username, and imap-password arguments
+ version 0.7.0
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1
Sun Jun 12 17:17:06 AST 2011
+ added --imap-mailbox option to pass through to check_imap_receive --mailbox option
+ added --ssl option to conveniently enable both --smtp-tls and --imap-ssl
+ version 0.7.2
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,258 @@
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>check_imap_quota - connects to an IMAP account and checks the quota</title>
<link rel="stylesheet" href="plainwhite.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:jonathan@greek.local" />
</head>
<body>
<!-- INDEX BEGIN -->
<div name="index">
<p><a name="__index__"></a></p>
<!--
<ul>
<li><a href="#name">NAME</a></li>
<li><a href="#synopsis">SYNOPSIS</a></li>
<li><a href="#options">OPTIONS</a></li>
<li><a href="#examples">EXAMPLES</a></li>
<ul>
<li><a href="#report_how_many_emails_are_in_the_mailbox">Report how many emails are in the mailbox</a></li>
<li><a href="#report_the_email_with_the_highest_value">Report the email with the highest value</a></li>
<li><a href="#troubleshoot_your_search_parameters">Troubleshoot your search parameters</a></li>
</ul>
<li><a href="#exit_codes">EXIT CODES</a></li>
<li><a href="#nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></li>
<li><a href="#see_also">SEE ALSO</a></li>
<li><a href="#changes">CHANGES</a></li>
<li><a href="#author">AUTHOR</a></li>
<li><a href="#copyright_and_license">COPYRIGHT AND LICENSE</a></li>
</ul>
-->
</div>
<!-- INDEX END -->
<p>
</p>
<hr />
<h1><a name="name">NAME</a></h1>
<p>check_imap_quota - connects to an IMAP account and checks the quota</p>
<p>
</p>
<hr />
<h1><a name="synopsis">SYNOPSIS</a></h1>
<pre>
check_imap_quota -vV
check_imap_quota -?
check_imap_quota --help</pre>
<p>
</p>
<hr />
<h1><a name="options">OPTIONS</a></h1>
<dl>
<dt><strong><a name="warning_seconds" class="item">--warning &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Warn if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 15 seconds.
Also known as: -w &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="critical_seconds" class="item">--critical &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Return a critical status if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical &lt;messages&gt;
Also known as: -c &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="timeout_seconds" class="item">--timeout &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Abort with critical status if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="hostname_server" class="item">--hostname &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H &lt;server&gt;</p>
</dd>
<dt><strong><a name="port_number" class="item">--port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p &lt;number&gt;</p>
</dd>
<dt><strong><a name="username_username" class="item">--username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="password_password" class="item">--password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to IMAP server.
Also known as: -U &lt;username&gt; -P &lt;password&gt;</p>
</dd>
<dt><strong><a name="mailbox_mailbox" class="item">--mailbox &lt;mailbox&gt;</a></strong></dt>
<dd>
<p>Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m &lt;mailbox&gt;</p>
</dd>
<dt><strong><a name="ssl" class="item">--ssl</a></strong></dt>
<dt><strong><a name="nossl" class="item">--nossl</a></strong></dt>
<dd>
<p>Enable SSL protocol. Requires IO::Socket::SSL.</p>
<p>Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.</p>
<p>Use the nossl option to turn off the ssl option.</p>
</dd>
<dt><strong><a name="hires" class="item">--hires</a></strong></dt>
<dd>
<p>Use the Time::HiRes module to measure time, if available.</p>
</dd>
<dt><strong><a name="verbose" class="item">--verbose</a></strong></dt>
<dd>
<p>Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.</p>
<p>If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.</p>
<p>Also known as: -v</p>
</dd>
<dt><strong><a name="version" class="item">--version</a></strong></dt>
<dd>
<p>Display plugin version and exit.
Also known as: -V</p>
</dd>
<dt><strong><a name="help" class="item">--help</a></strong></dt>
<dd>
<p>Display this documentation and exit. Does not work in the ePN version.
Also known as: -h</p>
</dd>
<dt><strong><a name="usage" class="item">--usage</a></strong></dt>
<dd>
<p>Display a short usage instruction and exit.</p>
</dd>
</dl>
<p>
</p>
<hr />
<h1><a name="examples">EXAMPLES</a></h1>
<p>
</p>
<h2><a name="report_how_many_emails_are_in_the_mailbox">Report how many emails are in the mailbox</a></h2>
<pre>
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete</pre>
<pre>
IMAP RECEIVE OK - 1 seconds, 7 found</pre>
<p>
</p>
<h2><a name="report_the_email_with_the_highest_value">Report the email with the highest value</a></h2>
<p>Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):</p>
<pre>
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: &lt;auto-000000992528@server.net&gt;</pre>
<pre>
Homeruns 5</pre>
<p>And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:</p>
<pre>
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s &quot;Results of Autoscript&quot; --capture-max &quot;Homeruns (\d+)&quot; --nodelete-captured</pre>
<pre>
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted</pre>
<p>
</p>
<h2><a name="troubleshoot_your_search_parameters">Troubleshoot your search parameters</a></h2>
<p>Add the --nodelete and --imap-retries=1 parameters to your command line.</p>
<p>
</p>
<hr />
<h1><a name="exit_codes">EXIT CODES</a></h1>
<p><table cellspacing="0" cellpadding="0"><tr><td>Complies with the Nagios plug-in specification:
<tr><td> 0<td>OK<td>The plugin was able to check the service and it appeared to be functioning properly
<tr><td> 1<td>Warning<td>The plugin was able to check the service, but it appeared to be above some &quot;warning&quot; threshold or did not appear to be working properly
<tr><td> 2<td>Critical<td>The plugin detected that either the service was not running or it was above some &quot;critical&quot; threshold
<tr><td> 3<td>Unknown<td>Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service</table></p>
<p>
</p>
<hr />
<h1><a name="nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></h1>
<p>Nagios plugin reference: <a href="http://nagiosplug.sourceforge.net/developer-guidelines.html">http://nagiosplug.sourceforge.net/developer-guidelines.html</a></p>
<p>This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.</p>
<p>Other than that, it attempts to follow published guidelines for Nagios plugins.</p>
<p>
</p>
<hr />
<h1><a name="see_also">SEE ALSO</a></h1>
<p><a href="http://nagios.org/">http://nagios.org/</a>
<a href="http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod">http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod</a>
<a href="http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod">http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod</a></p>
<p>
</p>
<hr />
<h1><a name="changes">CHANGES</a></h1>
<pre>
Fri Nov 11 04:53:09 AST 2011
+ version 0.1 created with quota code contributed by Johan Romme</pre>
<pre>
Tue Dec 20 17:38:04 PST 2011
+ fixed bug where a quota of 0 was reported as an incorrect response from the server, thanks to Eike Arndt
+ version 0.2</pre>
<p>
</p>
<hr />
<h1><a name="author">AUTHOR</a></h1>
<p>Jonathan Buhacoff &lt;<a href="mailto:jonathan@buhacoff.net">jonathan@buhacoff.net</a>&gt;</p>
<p>
</p>
<hr />
<h1><a name="copyright_and_license">COPYRIGHT AND LICENSE</a></h1>
<pre>
Copyright (C) 2011 Jonathan Buhacoff</pre>
<pre>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.</pre>
<pre>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.</pre>
<pre>
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;<a href="http://www.gnu.org/licenses/&gt">http://www.gnu.org/licenses/&gt</a>;.</pre>
<pre>
<a href="http://www.gnu.org/licenses/gpl.txt">http://www.gnu.org/licenses/gpl.txt</a></pre>
</body>
</html>

View File

@ -0,0 +1,196 @@
=pod
=head1 NAME
check_imap_quota - connects to an IMAP account and checks the quota
=head1 SYNOPSIS
check_imap_quota -vV
check_imap_quota -?
check_imap_quota --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the IMAP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical <messages>
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
=item --mailbox <mailbox>
Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m <mailbox>
=item --ssl
=item --nossl
Enable SSL protocol. Requires IO::Socket::SSL.
Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.
Use the nossl option to turn off the ssl option.
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Report how many emails are in the mailbox
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete
IMAP RECEIVE OK - 1 seconds, 7 found
=head2 Report the email with the highest value
Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: <auto-000000992528@server.net>
Homeruns 5
And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s "Results of Autoscript" --capture-max "Homeruns (\d+)" --nodelete-captured
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted
=head2 Troubleshoot your search parameters
Add the --nodelete and --imap-retries=1 parameters to your command line.
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 SEE ALSO
http://nagios.org/
http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod
http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod
=head1 CHANGES
Fri Nov 11 04:53:09 AST 2011
+ version 0.1 created with quota code contributed by Johan Romme
Tue Dec 20 17:38:04 PST 2011
+ fixed bug where a quota of 0 was reported as an incorrect response from the server, thanks to Eike Arndt
+ version 0.2
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,551 @@
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>check_imap_receive - connects to and searches an IMAP account for messages</title>
<link rel="stylesheet" href="plainwhite.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:jonathan@greek.local" />
</head>
<body>
<!-- INDEX BEGIN -->
<div name="index">
<p><a name="__index__"></a></p>
<!--
<ul>
<li><a href="#name">NAME</a></li>
<li><a href="#synopsis">SYNOPSIS</a></li>
<li><a href="#options">OPTIONS</a></li>
<li><a href="#examples">EXAMPLES</a></li>
<ul>
<li><a href="#report_how_many_emails_are_in_the_mailbox">Report how many emails are in the mailbox</a></li>
<li><a href="#report_the_email_with_the_highest_value">Report the email with the highest value</a></li>
<li><a href="#troubleshoot_your_search_parameters">Troubleshoot your search parameters</a></li>
</ul>
<li><a href="#exit_codes">EXIT CODES</a></li>
<li><a href="#nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></li>
<li><a href="#see_also">SEE ALSO</a></li>
<li><a href="#changes">CHANGES</a></li>
<li><a href="#author">AUTHOR</a></li>
<li><a href="#copyright_and_license">COPYRIGHT AND LICENSE</a></li>
</ul>
-->
</div>
<!-- INDEX END -->
<p>
</p>
<hr />
<h1><a name="name">NAME</a></h1>
<p>check_imap_receive - connects to and searches an IMAP account for messages</p>
<p>
</p>
<hr />
<h1><a name="synopsis">SYNOPSIS</a></h1>
<pre>
check_imap_receive -vV
check_imap_receive -?
check_imap_receive --help</pre>
<p>
</p>
<hr />
<h1><a name="options">OPTIONS</a></h1>
<dl>
<dt><strong><a name="warning_seconds" class="item">--warning &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Warn if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 15 seconds.
Also known as: -w &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="critical_seconds" class="item">--critical &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Return a critical status if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical &lt;messages&gt;
Also known as: -c &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="timeout_seconds" class="item">--timeout &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Abort with critical status if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="imap_check_interval_seconds" class="item">--imap-check-interval &lt;seconds&gt;</a></strong></dt>
<dd>
<p>How long to wait after searching for a matching message before searching again. Only takes effect
if no messages were found. Default is 5 seconds.</p>
</dd>
<dt><strong><a name="imap_retries_number" class="item">--imap-retries &lt;number&gt;</a></strong></dt>
<dd>
<p>How many times to try searching for a matching message before giving up. If you set this to 0 then
messages will not be searched at all. Setting this to 1 means the plugin only tries once. Etc.
Default is 10 times.</p>
</dd>
<dt><strong><a name="hostname_server" class="item">--hostname &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H &lt;server&gt;</p>
</dd>
<dt><strong><a name="port_number" class="item">--port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p &lt;number&gt;</p>
</dd>
<dt><strong><a name="username_username" class="item">--username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="password_password" class="item">--password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to IMAP server.
Also known as: -U &lt;username&gt; -P &lt;password&gt;</p>
</dd>
<dt><strong><a name="mailbox_mailbox" class="item">--mailbox &lt;mailbox&gt;</a></strong></dt>
<dd>
<p>Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m &lt;mailbox&gt;</p>
</dd>
<dt><strong><a name="search_string" class="item">--search &lt;string&gt;</a></strong></dt>
<dd>
<p>Use this option to filter the messages. Default is not to filter. You may (must) use this option
multiple times in order to create any valid IMAP search criteria. See the examples and see also
<a href="http://www.ietf.org/rfc/rfc2060.txt">http://www.ietf.org/rfc/rfc2060.txt</a> (look for section 6.4.4, the SEARCH command)</p>
<p>This is the way to find messages matching a given subject:
-s SUBJECT -s &quot;a given subject&quot;</p>
<p>You can use the following technique for any header, including Subject. To find &quot;Header-Name: some value&quot;:
-s HEADER -s Header-Name -s &quot;some value&quot;</p>
<p>Modern IMAP servers that support rfc5032 extensions allow you to search for messages
older or younger than a number of seconds. So to find messages received in the past hour,
you can do:</p>
<pre>
-s YOUNGER -s 3600</pre>
<p>Or to find messages received more than 5 minutes ago, you can do:</p>
<pre>
-s OLDER -s 300</pre>
<p>Also known as: -s &lt;string&gt;</p>
</dd>
<dt><strong><a name="download" class="item">--download</a></strong></dt>
<dt><strong><a name="nodownload" class="item">--nodownload</a></strong></dt>
<dd>
<p>This option causes all messages in the specified mailbox to be downloaded from the server
and searched locally. See --download-max if you only want to download a few messages.
Currently only the following <a href="http://www.ietf.org/rfc/rfc2060.txt" class="rfc">RFC 2060</a> search criteria are supported:
TEXT, BODY, SUBJECT, HEADER, NOT, OR, SENTBEFORE, SENTON, SENTSINCE.</p>
<p>Requires Email::Simple to be installed. It is available on CPAN.</p>
<p>This option may be particularly useful to you if your mail server is slow to index
messages (like Exchange 2003), causing the plugin not to find them with IMAP SEARCH
even though they are in the inbox.</p>
<p>It's also useful if you're searching for messages that have been on the server for a
specified amount of time, like some minutes or hours, because the standard IMAP search
function only allows whole dates. For this, use the standard search keywords but you
can specify either just a date like in <a href="http://www.ietf.org/rfc/rfc2060.txt" class="rfc">RFC 2060</a> or a date and a time.</p>
<p>If you use SENTBEFORE, SENTON, or SENTSINCE, you must have Date::Manip installed
on your system.</p>
</dd>
<dt><strong><a name="download_max" class="item">--download-max</a></strong></dt>
<dd>
<p>Limits the number of messages downloaded from the server when the --download option is used.
Default is to download and search all messages.</p>
</dd>
<dt><strong><a name="search_critical_min_messages" class="item">--search-critical-min &lt;messages&gt;</a></strong></dt>
<dd>
<p>This option will trigger a CRITICAL status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.</p>
<p>This parameter defaults to 1 so that if no messages are found, the plugin will exit with a CRITICAL status.</p>
<p>If you want the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0.</p>
</dd>
<dt><strong><a name="search_critical_max_messages" class="item">--search-critical-max &lt;messages&gt;</a></strong></dt>
<dd>
<p>This option will trigger a CRITICAL status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.</p>
<p>This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
CRITICAL if it finds 11 messages. If you set it to 1, the plugin will exit with CRITICAL if it finds
any more than 1 message. If you set it to 0, the plugin will exit with CRITICAL if it finds any messages
at all. If you set it to -1 it will be disabled.</p>
</dd>
<dt><strong><a name="search_warning_min_messages" class="item">--search-warning-min &lt;messages&gt;</a></strong></dt>
<dd>
<p>This option will trigger a WARNING status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.</p>
<p>This parameter defaults to 1 so that if no messages are found, the plugin will exit with a WARNING status.</p>
<p>If you want to suppress the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0. When this parameter is 0, it means that you expect the mailbox not to have any messages.</p>
</dd>
<dt><strong><a name="search_warning_max_messages" class="item">--search-warning-max &lt;messages&gt;</a></strong></dt>
<dd>
<p>This option will trigger a WARNING status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.</p>
<p>This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
WARNING if it finds 11 messages. If you set it to 1, the plugin will exit with WARNING if it finds
any more than 1 message. If you set it to 0, the plugin will exit with WARNING if it finds any messages
at all. If you set it to -1 it will be disabled.</p>
</dd>
<dt><strong><a name="capture_max_regexp" class="item">--capture-max &lt;regexp&gt;</a></strong></dt>
<dd>
<p>In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a &quot;capture-max&quot; regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the highest captured value.</p>
<p>The regexp is expected to capture a numeric value.</p>
</dd>
<dt><strong><a name="capture_min_regexp" class="item">--capture-min &lt;regexp&gt;</a></strong></dt>
<dd>
<p>In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a &quot;capture-min&quot; regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the lowest captured value.</p>
<p>The regexp is expected to capture a numeric value.</p>
</dd>
<dt><strong><a name="delete" class="item">--delete</a></strong></dt>
<dt><strong><a name="nodelete" class="item">--nodelete</a></strong></dt>
<dd>
<p>Use the delete option to delete messages that matched the search criteria. This is useful for
preventing the mailbox from filling up with automated messages (from the check_smtp_send plugin, for example).
THE DELETE OPTION IS TURNED *ON* BY DEFAULT, in order to preserve compatibility with an earlier version.</p>
<p>Use the nodelete option to turn off the delete option.</p>
</dd>
<dt><strong><a name="nodelete_captured" class="item">--nodelete-captured</a></strong></dt>
<dd>
<p>If you use both the capture-max and delete arguments, you can also use the nodelete-captured argument to specify that the email
with the highest captured value should not be deleted. This leaves it available for comparison the next time this plugin runs.</p>
<p>If you do not use the delete option, this option has no effect.</p>
</dd>
<dt><strong><a name="ssl" class="item">--ssl</a></strong></dt>
<dt><strong><a name="nossl" class="item">--nossl</a></strong></dt>
<dd>
<p>Enable SSL protocol. Requires IO::Socket::SSL.</p>
<p>Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.</p>
<p>Use the nossl option to turn off the ssl option.</p>
</dd>
<dt><strong><a name="ssl_ca_file" class="item">--ssl-ca-file</a></strong></dt>
<dd>
<p>Use this to verify the server SSL certificate against a local .pem file. You'll need to
specify the path to the .pem file as the parameter.</p>
<p>You can use the imap_ssl_cert utility included in this distribution to connect to your IMAP
server and save its SSL certificates into your .pem file. Usage is like this:</p>
<pre>
imap_ssl_cert -H imap.server.com &gt; ca_file.pem</pre>
<p>Only applicable when --ssl option is enabled.</p>
</dd>
<dt><strong><a name="template" class="item">--template</a></strong></dt>
<dt><strong><a name="notemplate" class="item">--notemplate</a></strong></dt>
<dd>
<p>Enable (or disable) processing of IMAP search parameters. Requires Text::Template and Date::Manip.</p>
<p>Use this option to apply special processing to IMAP search parameters that allows you to use the
results of arbitrary computations as the parameter values. For example, you can use this feature
to search for message received up to 4 hours ago.</p>
<p>Modern IMAP servers that support rfc5032 extensions allow searching with the YOUNGER and OLDER
criteria so a message received up to 4 hours ago is -s YOUNGER -s 14400. But if your mail server
doesn't support that, you could use the --template option to get similar functionality.</p>
<p>When you enable the --template option, each parameter you pass to the -s option is parsed by
Text::Template. See the Text::Template manual for more information, but in general any expression
written in Perl will work.</p>
<p>A convenience function called rfc2822dateHeader is provided to you so you can easily compute properly
formatted dates for use as search parameters. The rfc2822date function can take one or two
parameters itself: the date to format and an optional offset. To use the current time as a
search parameter, you can write this:</p>
<pre>
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{rfc2822dateHeader(&quot;now&quot;)}'</pre>
<p>The output of {rfc2822dateHeader(&quot;now&quot;)} looks like this: Wed, 30 Sep 2009 22:44:03 -0700 and
is suitable for use with a date header, like HEADER Delivery-Date.</p>
<p>To use a time in the past relative to the current time or day, you can use a second convenience function
called rfc2822date and write this:</p>
<pre>
$ check_imap_receive ... --template -s SENTSINCE -s '{rfc2822date(&quot;now&quot;,&quot;-1 day&quot;)}'</pre>
<p>The output of {rfc2822date(&quot;now&quot;,&quot;-1 day&quot;)} looks like this: 29-Sep-2009 and is suitable for use
with BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, and SINCE.</p>
<p>I have seen some email clients use a different format in the Date field,
like September 17, 2009 9:46:51 AM PDT. To specify an arbitrary format like this one, write this:</p>
<pre>
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{date(&quot;%B %e, %Y %i:%M:%S %p %Z&quot;,&quot;now&quot;,&quot;-4 hours&quot;)}'</pre>
<p>You can use BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, or SINCE to search for messages that arrived
on, before, or after a given day but not on, before, or after a specific time on that day.</p>
<p>To search for messages that arrived on, before, or after a specific time you have to use the
Delivery-Date or another date field, like with -s HEADER -s Delivery-Date in the example above.</p>
<p>See the Date::Manip manual for more information on the allowed expressions for date and delta strings.</p>
</dd>
<dt><strong><a name="hires" class="item">--hires</a></strong></dt>
<dd>
<p>Use the Time::HiRes module to measure time, if available.</p>
</dd>
<dt><strong><a name="verbose" class="item">--verbose</a></strong></dt>
<dd>
<p>Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.</p>
<p>If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.</p>
<p>Also known as: -v</p>
</dd>
<dt><strong><a name="version" class="item">--version</a></strong></dt>
<dd>
<p>Display plugin version and exit.
Also known as: -V</p>
</dd>
<dt><strong><a name="help" class="item">--help</a></strong></dt>
<dd>
<p>Display this documentation and exit. Does not work in the ePN version.
Also known as: -h</p>
</dd>
<dt><strong><a name="usage" class="item">--usage</a></strong></dt>
<dd>
<p>Display a short usage instruction and exit.</p>
</dd>
</dl>
<p>
</p>
<hr />
<h1><a name="examples">EXAMPLES</a></h1>
<p>
</p>
<h2><a name="report_how_many_emails_are_in_the_mailbox">Report how many emails are in the mailbox</a></h2>
<pre>
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete</pre>
<pre>
IMAP RECEIVE OK - 1 seconds, 7 found</pre>
<p>
</p>
<h2><a name="report_the_email_with_the_highest_value">Report the email with the highest value</a></h2>
<p>Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):</p>
<pre>
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: &lt;auto-000000992528@server.net&gt;</pre>
<pre>
Homeruns 5</pre>
<p>And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:</p>
<pre>
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s &quot;Results of Autoscript&quot; --capture-max &quot;Homeruns (\d+)&quot; --nodelete-captured</pre>
<pre>
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted</pre>
<p>
</p>
<h2><a name="troubleshoot_your_search_parameters">Troubleshoot your search parameters</a></h2>
<p>Add the --nodelete and --imap-retries=1 parameters to your command line.</p>
<p>
</p>
<hr />
<h1><a name="exit_codes">EXIT CODES</a></h1>
<p><table cellspacing="0" cellpadding="0"><tr><td>Complies with the Nagios plug-in specification:
<tr><td> 0<td>OK<td>The plugin was able to check the service and it appeared to be functioning properly
<tr><td> 1<td>Warning<td>The plugin was able to check the service, but it appeared to be above some &quot;warning&quot; threshold or did not appear to be working properly
<tr><td> 2<td>Critical<td>The plugin detected that either the service was not running or it was above some &quot;critical&quot; threshold
<tr><td> 3<td>Unknown<td>Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service</table></p>
<p>
</p>
<hr />
<h1><a name="nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></h1>
<p>Nagios plugin reference: <a href="http://nagiosplug.sourceforge.net/developer-guidelines.html">http://nagiosplug.sourceforge.net/developer-guidelines.html</a></p>
<p>This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.</p>
<p>Other than that, it attempts to follow published guidelines for Nagios plugins.</p>
<p>
</p>
<hr />
<h1><a name="see_also">SEE ALSO</a></h1>
<p><a href="http://nagios.org/">http://nagios.org/</a>
<a href="http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod">http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod</a>
<a href="http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod">http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod</a></p>
<p>
</p>
<hr />
<h1><a name="changes">CHANGES</a></h1>
<pre>
Wed Oct 29 11:00:00 PST 2005
+ version 0.1</pre>
<pre>
Wed Nov 9 09:53:32 PST 2005
+ added delete/nodelete option. deleting found messages is still default behavior.
+ added capture-max option
+ added nodelete-captured option
+ added mailbox option
+ added eval/alarm block to implement -c option
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2</pre>
<pre>
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson &lt;johann (at) axis.com&gt;)
+ version 0.2.1
+ added support for multiple polls of imap-server, with specified intervals</pre>
<pre>
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ added patch from Benjamin Ritcey &lt;ben@ritcey.com&gt; for SSL support on machines that have an SSL-enabled
+ version 0.2.3</pre>
<pre>
Fri Apr 27 18:56:50 PDT 2007
+ fixed problem that &quot;Invalid search parameters&quot; was not printed because of missing newline to flush it
+ warnings and critical errors now try to append error messages received from the IMAP client
+ changed connection error to display timeout only if timeout was the error
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ added abbreviations U for username, P for password, m for mailbox
+ fixed bug that imap-check-interval applied even after the last try (imap-retries) when it was not necessary
+ the IMAP expunge command is not sent unless at least one message is deleted
+ fixed bug that the &quot;no messages&quot; warning was printed even if some messages were found
+ version 0.3</pre>
<pre>
Sun Oct 21 14:08:07 PDT 2007
+ added port info to the &quot;could not connect&quot; error message
+ fixed bug that occurred when using --ssl --port 143 which caused port to remain at the default 993 imap/ssl port
+ added clarity shortcuts --search-subject and --search-header
+ port is no longer a required option. defaults to 143 for regular IMAP and 993 for IMAP/SSL
+ version 0.3.1</pre>
<pre>
Sun Oct 21 20:41:56 PDT 2007
+ reworked ssl support to use IO::Socket::SSL instead of the convenience method Mail::IMAPClient-&gt;Ssl (which is not included in the standard Mail::IMAPClient package)
+ removed clarity shortcuts (bad idea, code bloat)
+ version 0.4</pre>
<pre>
Tue Dec 4 07:05:27 PST 2007
+ added version check to _read_line workaround for SSL-related bug in Mail::IMAPClient version 2.2.9 ; newer versions fixed the bug
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.1</pre>
<pre>
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.4.2</pre>
<pre>
Mon Jan 7 21:35:23 PST 2008
+ changed version check for Mail::IMAPClient version 2.2.9 to use string comparison le &quot;2.2.9&quot;
+ fixed bug where script was dying on socket-&gt;autoflush when socket does not exist because autoflush was being called before checking the socket object
+ version 0.4.3</pre>
<pre>
Mon Feb 11 19:13:38 PST 2008
+ fixed a bug for embedded perl version, variable &quot;%status&quot; will not stay shared in load_modules
+ version 0.4.4</pre>
<pre>
Mon May 26 08:33:27 PDT 2008
+ fixed a bug for number captured, it now reflects number of messages captured instead of always returning &quot;1&quot;
+ added --capture-min option to complement --capture-max
+ added --search-critical-min to trigger a CRITICAL alert if number of messages found is less than argument, with default 1.
+ fixed warning and critical messages to use &quot;more than&quot; or &quot;less than&quot; instead of the angle brackets, to make them more web friendly
+ version 0.5</pre>
<pre>
Wed Jul 2 14:59:05 PDT 2008
+ fixed a bug for not finding a message after the first try, by reselecting the mailbox before each search
+ version 0.5.1</pre>
<pre>
Sat Dec 13 08:57:29 PST 2008
+ added --download option to allow local searching of messages (useful if your server has an index that handles searching but it takes a while before new emails show up and you want immediate results), supports only the TEXT, BODY, SUBJECT, and HEADER search keys
+ added --download-max option to set a limit on number of messages downloaded with --download
+ version 0.6.0</pre>
<pre>
Wed Sep 30 23:25:33 PDT 2009
+ fixed --download-max option (was incorrectly looking for --download_max). currently both will work, in the future only --download-max will work
+ added --template option to allow arbitrary substitutions for search parameters, and provided three convenience functions for working with dates
+ added date search criteria to the --download option: SENTBEFORE, SENTON, and SENTSINCE which check the Date header and allow hours and minutes in addition to dates (whereas the IMAP standard only allows dates)
+ added --search-critical-max to trigger a CRITICAL alert if number of messages found is more than argument, disabled by default.
+ fixed a bug in --download --search where messages would match even though they failed the search criteria
+ changed behavior of --download-max to look at the most recent messages first (hopefully); the IMAP protocol doesn't guarantee the order that the messages are returned but I observed that many mail servers return them in chronological order; so now --download-max reverses the order to look at the newer messages first
+ added performance data for use with PNP4Nagios!
+ version 0.7.0</pre>
<pre>
Fri Oct 2 15:22:00 PDT 2009
+ added --search-warning-max and --search-warning-min to trigger a WARNING alert if number of messages is more than or less than the specified number.
+ fixed --download option not to fail with CRITICAL if mailbox is empty; now this can be configured with --search-warning-min or --search-critical-min
+ version 0.7.1</pre>
<pre>
Sat Nov 21 18:27:17 PST 2009
+ fixed problem with using --download option on certain mail servers by turning on the IgnoreSizeErrors feature in IMAPClient
+ added --peek option to prevent marking messages as seen
+ version 0.7.2</pre>
<pre>
Tue Jan 5 12:13:53 PST 2010
+ added error message and exit with unknown status when an unrecognized IMAP search criteria is encountered by the --download --search option</pre>
<pre>
Wed May 5 11:14:51 PDT 2010
+ added mailbox list when mailbox is not found and verbose level 3 is on (-vvv)
+ version 0.7.3</pre>
<pre>
Tue Mar 8 18:58:14 AST 2011
+ updated documentation for --search and --template to mention rfc5032 extensions (thanks to Stuart Henderson)</pre>
<pre>
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.4</pre>
<pre>
Fri Nov 11 01:51:40 AST 2011
+ added --ssl-ca-file option to allow verifying the server certificate against a local .pem file (thanks to Alexandre Bezroutchko)
+ added imap_ssl_cert.pl utility (not in this file) to conveniently save the server's SSL certificates into a local .pem file
+ version 0.7.5</pre>
<p>
</p>
<hr />
<h1><a name="author">AUTHOR</a></h1>
<p>Jonathan Buhacoff &lt;<a href="mailto:jonathan@buhacoff.net">jonathan@buhacoff.net</a>&gt;</p>
<p>
</p>
<hr />
<h1><a name="copyright_and_license">COPYRIGHT AND LICENSE</a></h1>
<pre>
Copyright (C) 2005-2011 Jonathan Buhacoff</pre>
<pre>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.</pre>
<pre>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.</pre>
<pre>
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;<a href="http://www.gnu.org/licenses/&gt">http://www.gnu.org/licenses/&gt</a>;.</pre>
<pre>
<a href="http://www.gnu.org/licenses/gpl.txt">http://www.gnu.org/licenses/gpl.txt</a></pre>
</body>
</html>

View File

@ -0,0 +1,507 @@
=pod
=head1 NAME
check_imap_receive - connects to and searches an IMAP account for messages
=head1 SYNOPSIS
check_imap_receive -vV
check_imap_receive -?
check_imap_receive --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the IMAP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 30 seconds.
See also: --capture-critical <messages>
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --imap-check-interval <seconds>
How long to wait after searching for a matching message before searching again. Only takes effect
if no messages were found. Default is 5 seconds.
=item --imap-retries <number>
How many times to try searching for a matching message before giving up. If you set this to 0 then
messages will not be searched at all. Setting this to 1 means the plugin only tries once. Etc.
Default is 10 times.
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --username <username>
=item --password <password>
Username and password to use when connecting to IMAP server.
Also known as: -U <username> -P <password>
=item --mailbox <mailbox>
Use this option to specify the mailbox to search for messages. Default is INBOX.
Also known as: -m <mailbox>
=item --search <string>
Use this option to filter the messages. Default is not to filter. You may (must) use this option
multiple times in order to create any valid IMAP search criteria. See the examples and see also
http://www.ietf.org/rfc/rfc2060.txt (look for section 6.4.4, the SEARCH command)
This is the way to find messages matching a given subject:
-s SUBJECT -s "a given subject"
You can use the following technique for any header, including Subject. To find "Header-Name: some value":
-s HEADER -s Header-Name -s "some value"
Modern IMAP servers that support rfc5032 extensions allow you to search for messages
older or younger than a number of seconds. So to find messages received in the past hour,
you can do:
-s YOUNGER -s 3600
Or to find messages received more than 5 minutes ago, you can do:
-s OLDER -s 300
Also known as: -s <string>
=item --download
=item --nodownload
This option causes all messages in the specified mailbox to be downloaded from the server
and searched locally. See --download-max if you only want to download a few messages.
Currently only the following RFC 2060 search criteria are supported:
TEXT, BODY, SUBJECT, HEADER, NOT, OR, SENTBEFORE, SENTON, SENTSINCE.
Requires Email::Simple to be installed. It is available on CPAN.
This option may be particularly useful to you if your mail server is slow to index
messages (like Exchange 2003), causing the plugin not to find them with IMAP SEARCH
even though they are in the inbox.
It's also useful if you're searching for messages that have been on the server for a
specified amount of time, like some minutes or hours, because the standard IMAP search
function only allows whole dates. For this, use the standard search keywords but you
can specify either just a date like in RFC 2060 or a date and a time.
If you use SENTBEFORE, SENTON, or SENTSINCE, you must have Date::Manip installed
on your system.
=item --download-max
Limits the number of messages downloaded from the server when the --download option is used.
Default is to download and search all messages.
=item --search-critical-min <messages>
This option will trigger a CRITICAL status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.
This parameter defaults to 1 so that if no messages are found, the plugin will exit with a CRITICAL status.
If you want the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0.
=item --search-critical-max <messages>
This option will trigger a CRITICAL status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.
This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
CRITICAL if it finds 11 messages. If you set it to 1, the plugin will exit with CRITICAL if it finds
any more than 1 message. If you set it to 0, the plugin will exit with CRITICAL if it finds any messages
at all. If you set it to -1 it will be disabled.
=item --search-warning-min <messages>
This option will trigger a WARNING status if the number of messages found by the search criteria
is below the given number. Use in conjunction with --search.
This parameter defaults to 1 so that if no messages are found, the plugin will exit with a WARNING status.
If you want to suppress the original behavior where the plugin exits with a WARNING status when no messages are found,
set this parameter to 0. When this parameter is 0, it means that you expect the mailbox not to have any messages.
=item --search-warning-max <messages>
This option will trigger a WARNING status if the number of messages found by the search criteria
is above the given number. Use in conjunction with --search.
This parameter defaults to -1 meaning it's disabled. If you set it to 10, the plugin will exit with
WARNING if it finds 11 messages. If you set it to 1, the plugin will exit with WARNING if it finds
any more than 1 message. If you set it to 0, the plugin will exit with WARNING if it finds any messages
at all. If you set it to -1 it will be disabled.
=item --capture-max <regexp>
In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a "capture-max" regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the highest captured value.
The regexp is expected to capture a numeric value.
=item --capture-min <regexp>
In addition to specifying search arguments to filter the emails in the IMAP account, you can specify
a "capture-min" regexp argument and the eligible emails (found with search arguments)
will be compared to each other and the OK line will have the lowest captured value.
The regexp is expected to capture a numeric value.
=item --delete
=item --nodelete
Use the delete option to delete messages that matched the search criteria. This is useful for
preventing the mailbox from filling up with automated messages (from the check_smtp_send plugin, for example).
THE DELETE OPTION IS TURNED *ON* BY DEFAULT, in order to preserve compatibility with an earlier version.
Use the nodelete option to turn off the delete option.
=item --nodelete-captured
If you use both the capture-max and delete arguments, you can also use the nodelete-captured argument to specify that the email
with the highest captured value should not be deleted. This leaves it available for comparison the next time this plugin runs.
If you do not use the delete option, this option has no effect.
=item --ssl
=item --nossl
Enable SSL protocol. Requires IO::Socket::SSL.
Using this option automatically changes the default port from 143 to 993. You can still
override this from the command line using the --port option.
Use the nossl option to turn off the ssl option.
=item --ssl-ca-file
Use this to verify the server SSL certificate against a local .pem file. You'll need to
specify the path to the .pem file as the parameter.
You can use the imap_ssl_cert utility included in this distribution to connect to your IMAP
server and save its SSL certificates into your .pem file. Usage is like this:
imap_ssl_cert -H imap.server.com > ca_file.pem
Only applicable when --ssl option is enabled.
=item --template
=item --notemplate
Enable (or disable) processing of IMAP search parameters. Requires Text::Template and Date::Manip.
Use this option to apply special processing to IMAP search parameters that allows you to use the
results of arbitrary computations as the parameter values. For example, you can use this feature
to search for message received up to 4 hours ago.
Modern IMAP servers that support rfc5032 extensions allow searching with the YOUNGER and OLDER
criteria so a message received up to 4 hours ago is -s YOUNGER -s 14400. But if your mail server
doesn't support that, you could use the --template option to get similar functionality.
When you enable the --template option, each parameter you pass to the -s option is parsed by
Text::Template. See the Text::Template manual for more information, but in general any expression
written in Perl will work.
A convenience function called rfc2822dateHeader is provided to you so you can easily compute properly
formatted dates for use as search parameters. The rfc2822date function can take one or two
parameters itself: the date to format and an optional offset. To use the current time as a
search parameter, you can write this:
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{rfc2822dateHeader("now")}'
The output of {rfc2822dateHeader("now")} looks like this: Wed, 30 Sep 2009 22:44:03 -0700 and
is suitable for use with a date header, like HEADER Delivery-Date.
To use a time in the past relative to the current time or day, you can use a second convenience function
called rfc2822date and write this:
$ check_imap_receive ... --template -s SENTSINCE -s '{rfc2822date("now","-1 day")}'
The output of {rfc2822date("now","-1 day")} looks like this: 29-Sep-2009 and is suitable for use
with BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, and SINCE.
I have seen some email clients use a different format in the Date field,
like September 17, 2009 9:46:51 AM PDT. To specify an arbitrary format like this one, write this:
$ check_imap_receive ... --template -s HEADER -s Delivery-Date -s '{date("%B %e, %Y %i:%M:%S %p %Z","now","-4 hours")}'
You can use BEFORE, ON, SENTBEFORE, SENTON, SENTSINCE, or SINCE to search for messages that arrived
on, before, or after a given day but not on, before, or after a specific time on that day.
To search for messages that arrived on, before, or after a specific time you have to use the
Delivery-Date or another date field, like with -s HEADER -s Delivery-Date in the example above.
See the Date::Manip manual for more information on the allowed expressions for date and delta strings.
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting. Use together with --version to see the default
warning and critical timeout values.
If the selected mailbox was not found, you can use verbosity level 3 (-vvv) to display a list of all
available mailboxes on the server.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Report how many emails are in the mailbox
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s ALL --nodelete
IMAP RECEIVE OK - 1 seconds, 7 found
=head2 Report the email with the highest value
Suppose your mailbox has some emails from an automated script and that a message
from this script typically looks like this (abbreviated):
To: mailuser@server.net
From: autoscript@server.net
Subject: Results of Autoscript
Date: Wed, 09 Nov 2005 08:30:40 -0800
Message-ID: <auto-000000992528@server.net>
Homeruns 5
And further suppose that you are interested in reporting the message that has the
highest number of home runs, and also to leave this message in the mailbox for future
checks, but remove the other matching messages with lesser values:
$ check_imap_receive -H mail.server.net --username mailuser --password mailpass
-s SUBJECT -s "Results of Autoscript" --capture-max "Homeruns (\d+)" --nodelete-captured
IMAP RECEIVE OK - 1 seconds, 3 found, 1 captured, 5 max, 2 deleted
=head2 Troubleshoot your search parameters
Add the --nodelete and --imap-retries=1 parameters to your command line.
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 SEE ALSO
http://nagios.org/
http://search.cpan.org/~djkernen/Mail-IMAPClient-2.2.9/IMAPClient.pod
http://search.cpan.org/~markov/Mail-IMAPClient-3.00/lib/Mail/IMAPClient.pod
=head1 CHANGES
Wed Oct 29 11:00:00 PST 2005
+ version 0.1
Wed Nov 9 09:53:32 PST 2005
+ added delete/nodelete option. deleting found messages is still default behavior.
+ added capture-max option
+ added nodelete-captured option
+ added mailbox option
+ added eval/alarm block to implement -c option
+ now using an inline PluginReport package to generate the report
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 14:00:00 CET 2006 (by Johan Nilsson <johann (at) axis.com>)
+ version 0.2.1
+ added support for multiple polls of imap-server, with specified intervals
Tue Apr 24 21:17:53 PDT 2007
+ now there is an alternate version (same but without embedded perl POD) that is compatible with the new new embedded-perl Nagios feature
+ added patch from Benjamin Ritcey <ben@ritcey.com> for SSL support on machines that have an SSL-enabled
+ version 0.2.3
Fri Apr 27 18:56:50 PDT 2007
+ fixed problem that "Invalid search parameters" was not printed because of missing newline to flush it
+ warnings and critical errors now try to append error messages received from the IMAP client
+ changed connection error to display timeout only if timeout was the error
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ added abbreviations U for username, P for password, m for mailbox
+ fixed bug that imap-check-interval applied even after the last try (imap-retries) when it was not necessary
+ the IMAP expunge command is not sent unless at least one message is deleted
+ fixed bug that the "no messages" warning was printed even if some messages were found
+ version 0.3
Sun Oct 21 14:08:07 PDT 2007
+ added port info to the "could not connect" error message
+ fixed bug that occurred when using --ssl --port 143 which caused port to remain at the default 993 imap/ssl port
+ added clarity shortcuts --search-subject and --search-header
+ port is no longer a required option. defaults to 143 for regular IMAP and 993 for IMAP/SSL
+ version 0.3.1
Sun Oct 21 20:41:56 PDT 2007
+ reworked ssl support to use IO::Socket::SSL instead of the convenience method Mail::IMAPClient->Ssl (which is not included in the standard Mail::IMAPClient package)
+ removed clarity shortcuts (bad idea, code bloat)
+ version 0.4
Tue Dec 4 07:05:27 PST 2007
+ added version check to _read_line workaround for SSL-related bug in Mail::IMAPClient version 2.2.9 ; newer versions fixed the bug
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.1
Sat Dec 15 07:39:59 PST 2007
+ improved compatibility with Nagios embedded perl (ePN)
+ version 0.4.2
Mon Jan 7 21:35:23 PST 2008
+ changed version check for Mail::IMAPClient version 2.2.9 to use string comparison le "2.2.9"
+ fixed bug where script was dying on socket->autoflush when socket does not exist because autoflush was being called before checking the socket object
+ version 0.4.3
Mon Feb 11 19:13:38 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.4.4
Mon May 26 08:33:27 PDT 2008
+ fixed a bug for number captured, it now reflects number of messages captured instead of always returning "1"
+ added --capture-min option to complement --capture-max
+ added --search-critical-min to trigger a CRITICAL alert if number of messages found is less than argument, with default 1.
+ fixed warning and critical messages to use "more than" or "less than" instead of the angle brackets, to make them more web friendly
+ version 0.5
Wed Jul 2 14:59:05 PDT 2008
+ fixed a bug for not finding a message after the first try, by reselecting the mailbox before each search
+ version 0.5.1
Sat Dec 13 08:57:29 PST 2008
+ added --download option to allow local searching of messages (useful if your server has an index that handles searching but it takes a while before new emails show up and you want immediate results), supports only the TEXT, BODY, SUBJECT, and HEADER search keys
+ added --download-max option to set a limit on number of messages downloaded with --download
+ version 0.6.0
Wed Sep 30 23:25:33 PDT 2009
+ fixed --download-max option (was incorrectly looking for --download_max). currently both will work, in the future only --download-max will work
+ added --template option to allow arbitrary substitutions for search parameters, and provided three convenience functions for working with dates
+ added date search criteria to the --download option: SENTBEFORE, SENTON, and SENTSINCE which check the Date header and allow hours and minutes in addition to dates (whereas the IMAP standard only allows dates)
+ added --search-critical-max to trigger a CRITICAL alert if number of messages found is more than argument, disabled by default.
+ fixed a bug in --download --search where messages would match even though they failed the search criteria
+ changed behavior of --download-max to look at the most recent messages first (hopefully); the IMAP protocol doesn't guarantee the order that the messages are returned but I observed that many mail servers return them in chronological order; so now --download-max reverses the order to look at the newer messages first
+ added performance data for use with PNP4Nagios!
+ version 0.7.0
Fri Oct 2 15:22:00 PDT 2009
+ added --search-warning-max and --search-warning-min to trigger a WARNING alert if number of messages is more than or less than the specified number.
+ fixed --download option not to fail with CRITICAL if mailbox is empty; now this can be configured with --search-warning-min or --search-critical-min
+ version 0.7.1
Sat Nov 21 18:27:17 PST 2009
+ fixed problem with using --download option on certain mail servers by turning on the IgnoreSizeErrors feature in IMAPClient
+ added --peek option to prevent marking messages as seen
+ version 0.7.2
Tue Jan 5 12:13:53 PST 2010
+ added error message and exit with unknown status when an unrecognized IMAP search criteria is encountered by the --download --search option
Wed May 5 11:14:51 PDT 2010
+ added mailbox list when mailbox is not found and verbose level 3 is on (-vvv)
+ version 0.7.3
Tue Mar 8 18:58:14 AST 2011
+ updated documentation for --search and --template to mention rfc5032 extensions (thanks to Stuart Henderson)
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.4
Fri Nov 11 01:51:40 AST 2011
+ added --ssl-ca-file option to allow verifying the server certificate against a local .pem file (thanks to Alexandre Bezroutchko)
+ added imap_ssl_cert.pl utility (not in this file) to conveniently save the server's SSL certificates into a local .pem file
+ version 0.7.5
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,375 @@
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>check_smtp_send - connects to an SMTP server and sends a message</title>
<link rel="stylesheet" href="plainwhite.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:jonathan@greek.local" />
</head>
<body>
<!-- INDEX BEGIN -->
<div name="index">
<p><a name="__index__"></a></p>
<!--
<ul>
<li><a href="#name">NAME</a></li>
<li><a href="#synopsis">SYNOPSIS</a></li>
<li><a href="#options">OPTIONS</a></li>
<li><a href="#examples">EXAMPLES</a></li>
<ul>
<li><a href="#send_a_message_with_custom_headers">Send a message with custom headers</a></li>
</ul>
<li><a href="#exit_codes">EXIT CODES</a></li>
<li><a href="#nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></li>
<li><a href="#changes">CHANGES</a></li>
<li><a href="#author">AUTHOR</a></li>
<li><a href="#copyright_and_license">COPYRIGHT AND LICENSE</a></li>
</ul>
-->
</div>
<!-- INDEX END -->
<p>
</p>
<hr />
<h1><a name="name">NAME</a></h1>
<p>check_smtp_send - connects to an SMTP server and sends a message</p>
<p>
</p>
<hr />
<h1><a name="synopsis">SYNOPSIS</a></h1>
<pre>
check_smtp_send -vV
check_smtp_send -?
check_smtp_send --help</pre>
<p>
</p>
<hr />
<h1><a name="options">OPTIONS</a></h1>
<dl>
<dt><strong><a name="warning_seconds" class="item">--warning &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Warn if it takes longer than &lt;seconds&gt; to connect to the SMTP server. Default is 15 seconds.
Also known as: -w &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="critical_seconds" class="item">--critical &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Return a critical status if it takes longer than &lt;seconds&gt; to connect to the SMTP server. Default is 30 seconds.
Also known as: -c &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="timeout_seconds" class="item">--timeout &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Abort with critical status if it takes longer than &lt;seconds&gt; to connect to the SMTP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="hostname_server" class="item">--hostname &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the SMTP server. Examples: mail.server.com, localhost, 192.168.1.100</p>
<p>If not provided, and if there is only one --mailto address, the script will automatically look up the MX record
for the --mailto address and use that as the hostname. You can use this to check that your MX records are correct.
When omitting the --hostname option, it doesn't really make sense to specify --port, --username, or --password
but you can still do so and they will have their normal effect. To look up the MX records you need to have the
module Net::DNS and Email::Address installed.</p>
<p>Also known as: -H &lt;server&gt;</p>
</dd>
<dt><strong><a name="port_number" class="item">--port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the SMTP server. Default is 25 for regular SMTP, 465 for SSL, and 587 for TLS.
Also known as: -p &lt;number&gt;</p>
</dd>
<dt><strong><a name="tls" class="item">--tls</a></strong></dt>
<dt><strong><a name="notls" class="item">--notls</a></strong></dt>
<dd>
<p>Enable TLS/AUTH protocol. Requires Net::SMTP::TLS, availble on CPAN.</p>
<p>When using this option, the default port is 587.
You can specify a port from the command line using the --port option.</p>
<p>Use the notls option to turn off the tls option.</p>
<p>Also, you may need to fix your copy of Net::SMTP::TLS. Here is the diff against version 0.12:</p>
<pre>
254c254
&lt; $me-&gt;_command(sprintf(&quot;AUTH PLAIN %S&quot;,
---
&gt; $me-&gt;_command(sprintf(&quot;AUTH PLAIN %s&quot;,</pre>
</dd>
<dt><strong><a name="ssl" class="item">--ssl</a></strong></dt>
<dt><strong><a name="nossl" class="item">--nossl</a></strong></dt>
<dd>
<p>Enable SSL protocol. Requires Net::SMTP::SSL and Authen::SASL, availble on CPAN.</p>
<p>When using this option, the default port is 465. You can override with the --port option.</p>
<p>Use the nossl option to turn off the ssl option.</p>
</dd>
<dt><strong><a name="auth_method" class="item">--auth &lt;method&gt;</a></strong></dt>
<dd>
<p>Enable authentication with Net::SMTP_auth (sold separately).
For example, try using --auth PLAIN or --auth CRAM-MD5.</p>
</dd>
<dt><strong><a name="username_username" class="item">--username &lt;username&gt;</a></strong></dt>
<dt><strong><a name="password_password" class="item">--password &lt;password&gt;</a></strong></dt>
<dd>
<p>Username and password to use when connecting to SMTP server.
Also known as: -U &lt;username&gt; -P &lt;password&gt;</p>
</dd>
<dt><strong><a name="body_message" class="item">--body &lt;message&gt;</a></strong></dt>
<dd>
<p>Use this option to specify the body of the email message. If you need newlines in your message,
you might need to use the --stdin option instead.</p>
</dd>
<dt><strong><a name="header_header" class="item">--header &lt;header&gt;</a></strong></dt>
<dd>
<p>Use this option to set an arbitrary header in the message. You can use it multiple times.</p>
</dd>
<dt><strong><a name="stdin" class="item">--stdin</a></strong></dt>
<dd>
<p>Grab the body of the email message from stdin.</p>
</dd>
<dt><strong><a name="mailto_recipient_your_net" class="item">--mailto <a href="mailto:recipient@your.net">recipient@your.net</a></a></strong></dt>
<dd>
<p>You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):</p>
<p>$ check_smtp_send -H mail.server.net --mailto <a href="mailto:recipient@your.net,recipient2@your.net">recipient@your.net,recipient2@your.net</a> --mailfrom <a href="mailto:sender@your.net">sender@your.net</a></p>
<p>SMTP SEND OK - 1 seconds</p>
</dd>
<dt><strong><a name="mailfrom_sender_your_net" class="item">--mailfrom <a href="mailto:sender@your.net">sender@your.net</a></a></strong></dt>
<dd>
<p>Use this option to set the &quot;from&quot; address in the email.</p>
</dd>
<dt><strong><a name="template" class="item">--template</a></strong></dt>
<dt><strong><a name="notemplate" class="item">--notemplate</a></strong></dt>
<dd>
<p>Enable (or disable) processing of message body and headers. Requires Text::Template.</p>
<p>Use this option to apply special processing to your message body and headers that allows you to use the
results of arbitrary computations in the text. For example, you can use this feature to send a message
containing the hostname of the machine that sent the message without customizing the plugin configuration
on each machine.</p>
<p>When you enable the --template option, the message body and headers are parsed by
Text::Template. Even a message body provided using the --stdin option will be parsed.
See the Text::Template manual for more information, but in general any expression
written in Perl will work.</p>
<p>There is one convenience function provided to you, trim, which will remove leading and trailing whitespace
from its parameter. Here's an example:</p>
<pre>
check_smtp_send -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--template --body 'hello, this message is from {use Sys::Hostname; hostname}'
--header 'Subject: test message from {trim(`whoami`)}'</pre>
</dd>
<dt><strong><a name="expect_response_code" class="item">--expect-response &lt;code&gt;</a></strong></dt>
<dd>
<p>Use this option to specify which SMTP response code should be expected from the server
after the SMTP dialog is complete. The default is 250 (message accepted).</p>
<p>Also known as: -E &lt;code&gt;</p>
</dd>
<dt><strong><a name="hires" class="item">--hires</a></strong></dt>
<dd>
<p>Use the Time::HiRes module to measure time, if available.</p>
</dd>
<dt><strong><a name="verbose" class="item">--verbose</a></strong></dt>
<dd>
<p>Display additional information. Useful for troubleshooting.</p>
<p>One --verbose will show extra information for OK, WARNING, and CRITICAL status.</p>
<p>Use one --verbose together with --version to see the default warning and critical timeout values.</p>
<p>Three --verbose (or -vvv) will show debug information, unless you're using --tls because Net::SMTP::TLS
does not have a Debug feature.</p>
<p>Also known as: -v</p>
</dd>
<dt><strong><a name="version" class="item">--version</a></strong></dt>
<dd>
<p>Display plugin version and exit.
Also known as: -V</p>
</dd>
<dt><strong><a name="help" class="item">--help</a></strong></dt>
<dd>
<p>Display this documentation and exit. Does not work in the ePN version.
Also known as: -h</p>
</dd>
<dt><strong><a name="usage" class="item">--usage</a></strong></dt>
<dd>
<p>Display a short usage instruction and exit.</p>
</dd>
</dl>
<p>
</p>
<hr />
<h1><a name="examples">EXAMPLES</a></h1>
<p>
</p>
<h2><a name="send_a_message_with_custom_headers">Send a message with custom headers</a></h2>
<p>$ check_smtp_send -H mail.server.net --mailto <a href="mailto:recipient@your.net">recipient@your.net</a> --mailfrom <a href="mailto:sender@your.net">sender@your.net</a>
--body 'Homeruns 5' --header 'Subject: Hello, world!' --header 'X-Your-Header: Yes'</p>
<p>SMTP SEND OK - 1 seconds</p>
<p>
</p>
<hr />
<h1><a name="exit_codes">EXIT CODES</a></h1>
<p><table cellspacing="0" cellpadding="0"><tr><td>Complies with the Nagios plug-in specification:
<tr><td> 0<td>OK<td>The plugin was able to check the service and it appeared to be functioning properly
<tr><td> 1<td>Warning<td>The plugin was able to check the service, but it appeared to be above some &quot;warning&quot; threshold or did not appear to be working properly
<tr><td> 2<td>Critical<td>The plugin detected that either the service was not running or it was above some &quot;critical&quot; threshold
<tr><td> 3<td>Unknown<td>Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service</table></p>
<p>
</p>
<hr />
<h1><a name="nagios_plugin_notes">NAGIOS PLUGIN NOTES</a></h1>
<p>Nagios plugin reference: <a href="http://nagiosplug.sourceforge.net/developer-guidelines.html">http://nagiosplug.sourceforge.net/developer-guidelines.html</a></p>
<p>This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.</p>
<p>Other than that, it attempts to follow published guidelines for Nagios plugins.</p>
<p>
</p>
<hr />
<h1><a name="changes">CHANGES</a></h1>
<pre>
Wed Oct 29 14:05:00 PST 2005
+ version 0.1</pre>
<pre>
Wed Nov 9 15:01:48 PST 2005
+ now using an inline PluginReport package to generate the report
+ added stdin option
+ copyright notice and GNU GPL
+ version 0.2</pre>
<pre>
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton &lt;geoff.crompton@strategicdata.com.au&gt;)
+ added bailing if the $smtp-&gt;to() call fails
+ added support for mailto recipients separated by commas
+ version 0.2.1</pre>
<pre>
Tue Apr 24 21:17:53 PDT 2007
+ moved POD text to separate file in order to accomodate the new embedded-perl Nagios feature
+ version 0.2.3</pre>
<pre>
Fri Apr 27 20:26:42 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ version 0.3
Sun Oct 21 10:34:14 PDT 2007
+ added support for TLS and authentication via the Net::SMTP::TLS module. see --tls option.
+ version 0.4</pre>
<pre>
Sun Oct 21 13:54:26 PDT 2007
+ added support for SSL via the Net::SMTP::SSL module. see --ssl option.
+ port is no longer a required option. defaults to 25 for regular smtp, 465 for ssl, and 587 for tls.
+ added port info to the &quot;could not connect&quot; error message
+ version 0.4.1</pre>
<pre>
Tue Dec 4 07:42:32 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.2</pre>
<pre>
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable &quot;%status&quot; will not stay shared in load_modules
+ version 0.4.3</pre>
<pre>
Mon May 26 09:12:14 PDT 2008
+ fixed warning and critical messages to use &quot;more than&quot; or &quot;less than&quot; instead of the angle brackets, to make them more web friendly
+ version 0.4.4
Wed Jul 2 07:12:35 PDT 2008
+ added --expect-response option submitted by Christian Kauhaus &lt;kc@gocept.com&gt;
+ added support for authentication via Net::SMTP_auth. see --auth option.
+ version 0.4.5</pre>
<pre>
Sun Oct 5 15:18:23 PDT 2008
+ added error handling for smtp server disconnects ungracefully during QUIT (gmail.com does)
+ version 0.4.6</pre>
<pre>
Thu Oct 1 12:09:35 PDT 2009
+ added --template option to allow arbitrary substitutions for body and headers, and provided one convenience function for trimming strings
+ added performance data for use with PNP4Nagios!
+ version 0.5.0</pre>
<pre>
Thu Oct 8 11:17:04 PDT 2009
+ added more detailed error messages when using --verbose
+ version 0.5.1</pre>
<pre>
Tue Feb 9 12:14:49 PST 2010
+ added support for combining --auth with --tls using a subclass of Net::SMTP::TLS submitted by Brad Guillory; please note that to use the &quot;PLAIN&quot; authentication type you need to patch your Net::SMTP:TLS because it has a bug in sub auth_PLAIN (sprintf %S instead of %s)
+ version 0.5.2</pre>
<pre>
Mon Jan 3 10:39:42 PST 2011
+ added default Date and Message-ID headers; Date header uses POSIX strftime and Message-ID header uses hostname command to get localhost name
+ version 0.7.0</pre>
<pre>
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1</pre>
<pre>
Wed Jul 6 19:18:26 AST 2011
+ the --hostname is now optional; if not provided the plugin will lookup the MX record for the --mailto address (requires Net::DNS)
+ version 0.7.2</pre>
<pre>
Tue Dec 13 09:24:04 PST 2011
+ separated authentication errors from connection errors
+ version 0.7.3</pre>
<p>
</p>
<hr />
<h1><a name="author">AUTHOR</a></h1>
<p>Jonathan Buhacoff &lt;<a href="mailto:jonathan@buhacoff.net">jonathan@buhacoff.net</a>&gt;</p>
<p>
</p>
<hr />
<h1><a name="copyright_and_license">COPYRIGHT AND LICENSE</a></h1>
<pre>
Copyright (C) 2005-2011 Jonathan Buhacoff</pre>
<pre>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.</pre>
<pre>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.</pre>
<pre>
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;<a href="http://www.gnu.org/licenses/&gt">http://www.gnu.org/licenses/&gt</a>;.</pre>
<pre>
<a href="http://www.gnu.org/licenses/gpl.txt">http://www.gnu.org/licenses/gpl.txt</a></pre>
</body>
</html>

View File

@ -0,0 +1,324 @@
=pod
=head1 NAME
check_smtp_send - connects to an SMTP server and sends a message
=head1 SYNOPSIS
check_smtp_send -vV
check_smtp_send -?
check_smtp_send --help
=head1 OPTIONS
=over
=item --warning <seconds>
Warn if it takes longer than <seconds> to connect to the SMTP server. Default is 15 seconds.
Also known as: -w <seconds>
=item --critical <seconds>
Return a critical status if it takes longer than <seconds> to connect to the SMTP server. Default is 30 seconds.
Also known as: -c <seconds>
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the SMTP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the SMTP server. Examples: mail.server.com, localhost, 192.168.1.100
If not provided, and if there is only one --mailto address, the script will automatically look up the MX record
for the --mailto address and use that as the hostname. You can use this to check that your MX records are correct.
When omitting the --hostname option, it doesn't really make sense to specify --port, --username, or --password
but you can still do so and they will have their normal effect. To look up the MX records you need to have the
module Net::DNS and Email::Address installed.
Also known as: -H <server>
=item --port <number>
Service port on the SMTP server. Default is 25 for regular SMTP, 465 for SSL, and 587 for TLS.
Also known as: -p <number>
=item --tls
=item --notls
Enable TLS/AUTH protocol. Requires Net::SMTP::TLS, availble on CPAN.
When using this option, the default port is 587.
You can specify a port from the command line using the --port option.
Use the notls option to turn off the tls option.
Also, you may need to fix your copy of Net::SMTP::TLS. Here is the diff against version 0.12:
254c254
< $me->_command(sprintf("AUTH PLAIN %S",
---
> $me->_command(sprintf("AUTH PLAIN %s",
=item --ssl
=item --nossl
Enable SSL protocol. Requires Net::SMTP::SSL and Authen::SASL, availble on CPAN.
When using this option, the default port is 465. You can override with the --port option.
Use the nossl option to turn off the ssl option.
=item --auth <method>
Enable authentication with Net::SMTP_auth (sold separately).
For example, try using --auth PLAIN or --auth CRAM-MD5.
=item --username <username>
=item --password <password>
Username and password to use when connecting to SMTP server.
Also known as: -U <username> -P <password>
=item --body <message>
Use this option to specify the body of the email message. If you need newlines in your message,
you might need to use the --stdin option instead.
=item --header <header>
Use this option to set an arbitrary header in the message. You can use it multiple times.
=item --stdin
Grab the body of the email message from stdin.
=item --mailto recipient@your.net
You can send a message to multiple recipients by repeating this option or by separating
the email addresses with commas (no whitespace allowed):
$ check_smtp_send -H mail.server.net --mailto recipient@your.net,recipient2@your.net --mailfrom sender@your.net
SMTP SEND OK - 1 seconds
=item --mailfrom sender@your.net
Use this option to set the "from" address in the email.
=item --template
=item --notemplate
Enable (or disable) processing of message body and headers. Requires Text::Template.
Use this option to apply special processing to your message body and headers that allows you to use the
results of arbitrary computations in the text. For example, you can use this feature to send a message
containing the hostname of the machine that sent the message without customizing the plugin configuration
on each machine.
When you enable the --template option, the message body and headers are parsed by
Text::Template. Even a message body provided using the --stdin option will be parsed.
See the Text::Template manual for more information, but in general any expression
written in Perl will work.
There is one convenience function provided to you, trim, which will remove leading and trailing whitespace
from its parameter. Here's an example:
check_smtp_send -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--template --body 'hello, this message is from {use Sys::Hostname; hostname}'
--header 'Subject: test message from {trim(`whoami`)}'
=item --expect-response <code>
Use this option to specify which SMTP response code should be expected from the server
after the SMTP dialog is complete. The default is 250 (message accepted).
Also known as: -E <code>
=item --hires
Use the Time::HiRes module to measure time, if available.
=item --verbose
Display additional information. Useful for troubleshooting.
One --verbose will show extra information for OK, WARNING, and CRITICAL status.
Use one --verbose together with --version to see the default warning and critical timeout values.
Three --verbose (or -vvv) will show debug information, unless you're using --tls because Net::SMTP::TLS
does not have a Debug feature.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit. Does not work in the ePN version.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Send a message with custom headers
$ check_smtp_send -H mail.server.net --mailto recipient@your.net --mailfrom sender@your.net
--body 'Homeruns 5' --header 'Subject: Hello, world!' --header 'X-Your-Header: Yes'
SMTP SEND OK - 1 seconds
=head1 EXIT CODES
Complies with the Nagios plug-in specification:
0 OK The plugin was able to check the service and it appeared to be functioning properly
1 Warning The plugin was able to check the service, but it appeared to be above some "warning" threshold or did not appear to be working properly
2 Critical The plugin detected that either the service was not running or it was above some "critical" threshold
3 Unknown Invalid command line arguments were supplied to the plugin or the plugin was unable to check the status of the given hosts/service
=head1 NAGIOS PLUGIN NOTES
Nagios plugin reference: http://nagiosplug.sourceforge.net/developer-guidelines.html
This plugin does NOT use Nagios DEFAULT_SOCKET_TIMEOUT (provided by utils.pm as $TIMEOUT) because
the path to utils.pm must be specified completely in this program and forces users to edit the source
code if their install location is different (if they realize this is the problem). You can view
the default timeout for this module by using the --verbose and --version options together. The
short form is -vV.
Other than that, it attempts to follow published guidelines for Nagios plugins.
=head1 CHANGES
Wed Oct 29 14:05:00 PST 2005
+ version 0.1
Wed Nov 9 15:01:48 PST 2005
+ now using an inline PluginReport package to generate the report
+ added stdin option
+ copyright notice and GNU GPL
+ version 0.2
Thu Apr 20 16:00:00 PST 2006 (by Geoff Crompton <geoff.crompton@strategicdata.com.au>)
+ added bailing if the $smtp->to() call fails
+ added support for mailto recipients separated by commas
+ version 0.2.1
Tue Apr 24 21:17:53 PDT 2007
+ moved POD text to separate file in order to accomodate the new embedded-perl Nagios feature
+ version 0.2.3
Fri Apr 27 20:26:42 PDT 2007
+ documentation now mentions every command-line option accepted by the plugin, including abbreviations
+ version 0.3
Sun Oct 21 10:34:14 PDT 2007
+ added support for TLS and authentication via the Net::SMTP::TLS module. see --tls option.
+ version 0.4
Sun Oct 21 13:54:26 PDT 2007
+ added support for SSL via the Net::SMTP::SSL module. see --ssl option.
+ port is no longer a required option. defaults to 25 for regular smtp, 465 for ssl, and 587 for tls.
+ added port info to the "could not connect" error message
+ version 0.4.1
Tue Dec 4 07:42:32 PST 2007
+ added --usage option because the official nagios plugins have both --help and --usage
+ added --timeout option to match the official nagios plugins
+ fixed some minor pod formatting issues for perldoc
+ version 0.4.2
Mon Feb 11 19:09:37 PST 2008
+ fixed a bug for embedded perl version, variable "%status" will not stay shared in load_modules
+ version 0.4.3
Mon May 26 09:12:14 PDT 2008
+ fixed warning and critical messages to use "more than" or "less than" instead of the angle brackets, to make them more web friendly
+ version 0.4.4
Wed Jul 2 07:12:35 PDT 2008
+ added --expect-response option submitted by Christian Kauhaus <kc@gocept.com>
+ added support for authentication via Net::SMTP_auth. see --auth option.
+ version 0.4.5
Sun Oct 5 15:18:23 PDT 2008
+ added error handling for smtp server disconnects ungracefully during QUIT (gmail.com does)
+ version 0.4.6
Thu Oct 1 12:09:35 PDT 2009
+ added --template option to allow arbitrary substitutions for body and headers, and provided one convenience function for trimming strings
+ added performance data for use with PNP4Nagios!
+ version 0.5.0
Thu Oct 8 11:17:04 PDT 2009
+ added more detailed error messages when using --verbose
+ version 0.5.1
Tue Feb 9 12:14:49 PST 2010
+ added support for combining --auth with --tls using a subclass of Net::SMTP::TLS submitted by Brad Guillory; please note that to use the "PLAIN" authentication type you need to patch your Net::SMTP:TLS because it has a bug in sub auth_PLAIN (sprintf %S instead of %s)
+ version 0.5.2
Mon Jan 3 10:39:42 PST 2011
+ added default Date and Message-ID headers; Date header uses POSIX strftime and Message-ID header uses hostname command to get localhost name
+ version 0.7.0
Fri May 6 08:35:09 AST 2011
+ added --hires option to enable use of Time::Hires if available
+ version 0.7.1
Wed Jul 6 19:18:26 AST 2011
+ the --hostname is now optional; if not provided the plugin will lookup the MX record for the --mailto address (requires Net::DNS)
+ version 0.7.2
Tue Dec 13 09:24:04 PST 2011
+ separated authentication errors from connection errors
+ version 0.7.3
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2005-2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,178 @@
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>imap_ssl_cert - connects to an IMAP server using SSL and saves the server certificate into a .pem file</title>
<link rel="stylesheet" href="plainwhite.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:jonathan@greek.local" />
</head>
<body>
<!-- INDEX BEGIN -->
<div name="index">
<p><a name="__index__"></a></p>
<!--
<ul>
<li><a href="#name">NAME</a></li>
<li><a href="#synopsis">SYNOPSIS</a></li>
<li><a href="#dependencies">DEPENDENCIES</a></li>
<li><a href="#options">OPTIONS</a></li>
<li><a href="#examples">EXAMPLES</a></li>
<ul>
<li><a href="#print_the_server_s_ssl_certificate_chain">Print the server's SSL certificate chain</a></li>
</ul>
<li><a href="#see_also">SEE ALSO</a></li>
<li><a href="#changes">CHANGES</a></li>
<li><a href="#author">AUTHOR</a></li>
<li><a href="#copyright_and_license">COPYRIGHT AND LICENSE</a></li>
</ul>
-->
</div>
<!-- INDEX END -->
<p>
</p>
<hr />
<h1><a name="name">NAME</a></h1>
<p>imap_ssl_cert - connects to an IMAP server using SSL and saves the server certificate into a .pem file</p>
<p>
</p>
<hr />
<h1><a name="synopsis">SYNOPSIS</a></h1>
<pre>
imap_ssl_cert -H imap.server.com &gt; server_ca_file.pem
imap_ssl_cert -?
imap_ssl_cert --help</pre>
<p>
</p>
<hr />
<h1><a name="dependencies">DEPENDENCIES</a></h1>
<p>This utility requires the following perl modules to be installed:</p>
<p>Getopt::Long
Mail::IMAPClient
IO::Socket::SSL
Net::SSLeay</p>
<p>
</p>
<hr />
<h1><a name="options">OPTIONS</a></h1>
<dl>
<dt><strong><a name="timeout_seconds" class="item">--timeout &lt;seconds&gt;</a></strong></dt>
<dd>
<p>Abort with critical status if it takes longer than &lt;seconds&gt; to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t &lt;seconds&gt;</p>
</dd>
<dt><strong><a name="hostname_server" class="item">--hostname &lt;server&gt;</a></strong></dt>
<dd>
<p>Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H &lt;server&gt;</p>
</dd>
<dt><strong><a name="port_number" class="item">--port &lt;number&gt;</a></strong></dt>
<dd>
<p>Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p &lt;number&gt;</p>
</dd>
<dt><strong><a name="verbose" class="item">--verbose</a></strong></dt>
<dd>
<p>Display additional information. Useful for troubleshooting.</p>
<p>Also known as: -v</p>
</dd>
<dt><strong><a name="version" class="item">--version</a></strong></dt>
<dd>
<p>Display plugin version and exit.
Also known as: -V</p>
</dd>
<dt><strong><a name="help" class="item">--help</a></strong></dt>
<dd>
<p>Display this documentation and exit.
Also known as: -h</p>
</dd>
<dt><strong><a name="usage" class="item">--usage</a></strong></dt>
<dd>
<p>Display a short usage instruction and exit.</p>
</dd>
</dl>
<p>
</p>
<hr />
<h1><a name="examples">EXAMPLES</a></h1>
<p>
</p>
<h2><a name="print_the_server_s_ssl_certificate_chain">Print the server's SSL certificate chain</a></h2>
<pre>
$ perl imap_ssl_cert.pl -H imap.server.com &gt; ca_file.pem
$ cat ca_file.pem</pre>
<pre>
-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIQPr3bVk0SkuXygjxgA7EVGDANBgkqhkiG9w0BAQUFADA8
[...snip...]
0FF4warjskrfqaVtWeIV58LJheaM4cPJkc2M
-----END CERTIFICATE-----</pre>
<pre>
$ openssl x509 -in ca_file.pem -text</pre>
<p>
</p>
<hr />
<h1><a name="see_also">SEE ALSO</a></h1>
<p><a href="http://en.wikipedia.org/wiki/X.509">http://en.wikipedia.org/wiki/X.509</a>
<a href="http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail">http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail</a>
<a href="http://tools.ietf.org/html/rfc1422">http://tools.ietf.org/html/rfc1422</a>
<a href="http://search.cpan.org/~mikem/Net-SSLeay-1.42/lib/Net/SSLeay.pm">http://search.cpan.org/~mikem/Net-SSLeay-1.42/lib/Net/SSLeay.pm</a>
<a href="http://search.cpan.org/~plobbes/Mail-IMAPClient-3.29/lib/Mail/IMAPClient.pod">http://search.cpan.org/~plobbes/Mail-IMAPClient-3.29/lib/Mail/IMAPClient.pod</a></p>
<p>
</p>
<hr />
<h1><a name="changes">CHANGES</a></h1>
<pre>
Fri Nov 11 03:38:13 AST 2011
+ version 0.1</pre>
<p>
</p>
<hr />
<h1><a name="author">AUTHOR</a></h1>
<p>Jonathan Buhacoff &lt;<a href="mailto:jonathan@buhacoff.net">jonathan@buhacoff.net</a>&gt;</p>
<p>
</p>
<hr />
<h1><a name="copyright_and_license">COPYRIGHT AND LICENSE</a></h1>
<pre>
Copyright (C) 2011 Jonathan Buhacoff</pre>
<pre>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.</pre>
<pre>
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.</pre>
<pre>
You should have received a copy of the GNU General Public License
along with this program. If not, see &lt;<a href="http://www.gnu.org/licenses/&gt">http://www.gnu.org/licenses/&gt</a>;.</pre>
<pre>
<a href="http://www.gnu.org/licenses/gpl.txt">http://www.gnu.org/licenses/gpl.txt</a></pre>
</body>
</html>

View File

@ -0,0 +1,122 @@
=pod
=head1 NAME
imap_ssl_cert - connects to an IMAP server using SSL and saves the server certificate into a .pem file
=head1 SYNOPSIS
imap_ssl_cert -H imap.server.com > server_ca_file.pem
imap_ssl_cert -?
imap_ssl_cert --help
=head1 DEPENDENCIES
This utility requires the following perl modules to be installed:
Getopt::Long
Mail::IMAPClient
IO::Socket::SSL
Net::SSLeay
=head1 OPTIONS
=over
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --verbose
Display additional information. Useful for troubleshooting.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Print the server's SSL certificate chain
$ perl imap_ssl_cert.pl -H imap.server.com > ca_file.pem
$ cat ca_file.pem
-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIQPr3bVk0SkuXygjxgA7EVGDANBgkqhkiG9w0BAQUFADA8
[...snip...]
0FF4warjskrfqaVtWeIV58LJheaM4cPJkc2M
-----END CERTIFICATE-----
$ openssl x509 -in ca_file.pem -text
=head1 SEE ALSO
http://en.wikipedia.org/wiki/X.509
http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail
http://tools.ietf.org/html/rfc1422
http://search.cpan.org/~mikem/Net-SSLeay-1.42/lib/Net/SSLeay.pm
http://search.cpan.org/~plobbes/Mail-IMAPClient-3.29/lib/Mail/IMAPClient.pod
=head1 CHANGES
Fri Nov 11 03:38:13 AST 2011
+ version 0.1
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,236 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.1';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
use Getopt::Long;
use Mail::IMAPClient;
use IO::Socket::SSL;
use Net::SSLeay;
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $timeout = 60;
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
# time
"t|timeout=i"=>\$timeout
);
if( $show_version ) {
print "$VERSION\n";
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $help_usage
||
( $imap_server eq "" )
) {
print "Usage: $0 -H host [-p port]\n";
exit $status{UNKNOWN};
}
my @certs = (); # we have to store the certs we get Net::SSLeay here so that we can output them in REVERSE order (server cert first, root cert last)
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
$imap_port = $default_imap_ssl_port unless $imap_port;
my $socket = IO::Socket::SSL->new(
PeerAddr => "$imap_server:$imap_port",
SSL_verify_mode => 1,
SSL_ca_file => undef,
SSL_verifycn_scheme => 'imap',
SSL_verifycn_name => $imap_server,
SSL_verify_callback => \&ssl_printer
);
die IO::Socket::SSL::errstr() unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
# $imap->User($username);
# $imap->Password($password);
# $imap->login() or die "Cannot login: $@";
print join("\n",reverse(@certs));
alarm 0;
};
if( $@ ) {
chomp $@;
print "Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
# deselect the mailbox
$imap->close();
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
exit $status{OK};
# see IO::Socket::SSL documentation for SSL_verify_callback:
sub ssl_printer {
my ($boolOpenSSLResult, $cmemCertificateStore, $strCertIssuerOwnerAttr, $strError, $cmemPeerCertificate) = @_;
warn "OpenSSL says certificate is " . ( $boolOpenSSLResult ? "valid" : "invalid" ) if $verbose > 0;
warn "Peer certificate: $strCertIssuerOwnerAttr" if $verbose > 0;
warn "Errors: $strError" if $verbose > 0;
#print Net::SSLeay::PEM_get_string_X509($cmemPeerCertificate);
push @certs, $strCertIssuerOwnerAttr . "\n" . Net::SSLeay::PEM_get_string_X509($cmemPeerCertificate);
}
package main;
1;
__END__
=pod
=head1 NAME
imap_ssl_cert - connects to an IMAP server using SSL and saves the server certificate into a .pem file
=head1 SYNOPSIS
imap_ssl_cert -H imap.server.com > server_ca_file.pem
imap_ssl_cert -?
imap_ssl_cert --help
=head1 DEPENDENCIES
This utility requires the following perl modules to be installed:
Getopt::Long
Mail::IMAPClient
IO::Socket::SSL
Net::SSLeay
=head1 OPTIONS
=over
=item --timeout <seconds>
Abort with critical status if it takes longer than <seconds> to connect to the IMAP server. Default is 60 seconds.
The difference between timeout and critical is that, with the default settings, if it takes 45 seconds to
connect to the server then the connection will succeed but the plugin will return CRITICAL because it took longer
than 30 seconds.
Also known as: -t <seconds>
=item --hostname <server>
Address or name of the IMAP server. Examples: mail.server.com, localhost, 192.168.1.100
Also known as: -H <server>
=item --port <number>
Service port on the IMAP server. Default is 143. If you use SSL, default is 993.
Also known as: -p <number>
=item --verbose
Display additional information. Useful for troubleshooting.
Also known as: -v
=item --version
Display plugin version and exit.
Also known as: -V
=item --help
Display this documentation and exit.
Also known as: -h
=item --usage
Display a short usage instruction and exit.
=back
=head1 EXAMPLES
=head2 Print the server's SSL certificate chain
$ perl imap_ssl_cert.pl -H imap.server.com > ca_file.pem
$ cat ca_file.pem
-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIQPr3bVk0SkuXygjxgA7EVGDANBgkqhkiG9w0BAQUFADA8
[...snip...]
0FF4warjskrfqaVtWeIV58LJheaM4cPJkc2M
-----END CERTIFICATE-----
$ openssl x509 -in ca_file.pem -text
=head1 SEE ALSO
http://en.wikipedia.org/wiki/X.509
http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail
http://tools.ietf.org/html/rfc1422
http://search.cpan.org/~mikem/Net-SSLeay-1.42/lib/Net/SSLeay.pm
http://search.cpan.org/~plobbes/Mail-IMAPClient-3.29/lib/Mail/IMAPClient.pod
=head1 CHANGES
Fri Nov 11 03:38:13 AST 2011
+ version 0.1
=head1 AUTHOR
Jonathan Buhacoff <jonathan@buhacoff.net>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2011 Jonathan Buhacoff
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
http://www.gnu.org/licenses/gpl.txt
=cut

View File

@ -0,0 +1,114 @@
#!/usr/bin/perl
use strict;
my $VERSION = '0.1';
my $COPYRIGHT = 'Copyright (C) 2005-2011 Jonathan Buhacoff <jonathan@buhacoff.net>';
my $LICENSE = 'http://www.gnu.org/licenses/gpl.txt';
my %status = ( 'OK' => 0, 'WARNING' => 1, 'CRITICAL' => 2, 'UNKNOWN' => 3 );
use Getopt::Long;
use Mail::IMAPClient;
use IO::Socket::SSL;
use Net::SSLeay;
# get options from command line
Getopt::Long::Configure("bundling");
my $verbose = 0;
my $help = "";
my $help_usage = "";
my $show_version = "";
my $imap_server = "";
my $default_imap_port = "143";
my $default_imap_ssl_port = "993";
my $imap_port = "";
my $timeout = 60;
my $ok;
$ok = Getopt::Long::GetOptions(
"V|version"=>\$show_version,
"v|verbose+"=>\$verbose,"h|help"=>\$help,"usage"=>\$help_usage,
# imap settings
"H|hostname=s"=>\$imap_server,"p|port=i"=>\$imap_port,
# time
"t|timeout=i"=>\$timeout
);
if( $show_version ) {
print "$VERSION\n";
exit $status{UNKNOWN};
}
if( $help ) {
exec "perldoc", $0 or print "Try `perldoc $0`\n";
exit $status{UNKNOWN};
}
if( $help_usage
||
( $imap_server eq "" )
) {
print "Usage: $0 -H host [-p port]\n";
exit $status{UNKNOWN};
}
my @certs = (); # we have to store the certs we get Net::SSLeay here so that we can output them in REVERSE order (server cert first, root cert last)
# connect to IMAP server
print "connecting to server $imap_server\n" if $verbose > 2;
my $imap;
eval {
local $SIG{ALRM} = sub { die "exceeded timeout $timeout seconds\n" }; # NB: \n required, see `perldoc -f alarm`
alarm $timeout;
$imap_port = $default_imap_ssl_port unless $imap_port;
my $socket = IO::Socket::SSL->new(
PeerAddr => "$imap_server:$imap_port",
SSL_verify_mode => 1,
SSL_ca_file => undef,
SSL_verifycn_scheme => 'imap',
SSL_verifycn_name => $imap_server,
SSL_verify_callback => \&ssl_printer
);
die IO::Socket::SSL::errstr() unless $socket;
$socket->autoflush(1);
$imap = Mail::IMAPClient->new(Socket=>$socket, Debug => 0 );
$imap->State(Mail::IMAPClient->Connected);
$imap->_read_line() if "$Mail::IMAPClient::VERSION" le "2.2.9"; # necessary to remove the server's "ready" line from the input buffer for old versions of Mail::IMAPClient. Using string comparison for the version check because the numeric didn't work on Darwin and for Mail::IMAPClient the next version is 2.3.0 and then 3.00 so string comparison works
# $imap->User($username);
# $imap->Password($password);
# $imap->login() or die "Cannot login: $@";
print join("\n",reverse(@certs));
alarm 0;
};
if( $@ ) {
chomp $@;
print "Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
unless( $imap ) {
print "Could not connect to $imap_server port $imap_port: $@\n";
exit $status{CRITICAL};
}
# deselect the mailbox
$imap->close();
# disconnect from IMAP server
print "disconnecting from server\n" if $verbose > 2;
$imap->logout();
exit $status{OK};
# see IO::Socket::SSL documentation for SSL_verify_callback:
sub ssl_printer {
my ($boolOpenSSLResult, $cmemCertificateStore, $strCertIssuerOwnerAttr, $strError, $cmemPeerCertificate) = @_;
warn "OpenSSL says certificate is " . ( $boolOpenSSLResult ? "valid" : "invalid" ) if $verbose > 0;
warn "Peer certificate: $strCertIssuerOwnerAttr" if $verbose > 0;
warn "Errors: $strError" if $verbose > 0;
#print Net::SSLeay::PEM_get_string_X509($cmemPeerCertificate);
push @certs, $strCertIssuerOwnerAttr . "\n" . Net::SSLeay::PEM_get_string_X509($cmemPeerCertificate);
}
package main;
1;

View File

@ -0,0 +1,63 @@
Summary: A Nagios plugin to check IMAP delivery times
#Name: check_email_delivery
Name: nagios-plugins-check_email_delivery
Version: 0.7.1a
Release: 0.2%{?dist}
License: GPLv2
Group: Applications/System
URL: http://buhacoff.net/software/check_email_delivery/
Source0: http://buhacoff.net/software/check_email_delivery/archive/check_email_delivery-%{version}.tar.gz
#http://exchange.nagios.org/components/com_mtree/attachment.php?link_id=1339&cf_id=30
BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root
# For handling --help options
Requires: /usr/bin/nroff
%description
The Nagios email delivery plugin uses two other plugins
(smtp send and imap receive), also included, to send a message
to an email account and then check that account for the message
and delete it. The plugin times how long it takes for the
message to be delivered and the warning and critical thresholds
are for this elapsed time.
%prep
#%setup -q
%setup -n check_email_delivery-%{version}
# Avoid filenames with unnecessary punction in them
%{__mv} "./docs/check_smtp_send (Greek's conflicted copy 2011-08-24).pod" \
./docs/check_smtp_send-Greeks-conflicted-copy-2011-08-24.pod
%{__mv} "docs/How to connect to IMAP server manually.txt" \
docs/How-to-connect-to-IMAP-server-manually.txt
%build
# No build required, just drop in place
%install
rm -rf $RPM_BUILD_ROOT
%{__install} -d -m0755 %{buildroot}%{_libdir}/nagios/plugins
# No instlalation procedure, install manually
%{__install} -m0755 -m0755 check_* %{buildroot}%{_libdir}/nagios/plugins
%{__install} -m0755 -m0755 imap_* %{buildroot}%{_libdir}/nagios/plugins
%clean
rm -rf $RPM_BUILD_ROOT
%files
%defattr(-, root, root, 0755)
%{_libdir}/nagios/plugins/check_*
%{_libdir}/nagios/plugins/imap_*
%doc CHANGES.txt LICENSE.txt README.txt
%doc docs/*
%changelog
* Sun Feb 5 2012 Nico Kadel-Garcia <nkadel@nkadel-sl6.localdomain> - 0.68-0.1
- Update to 0.7.1a
- Add nroff dependency for --help options
* Thu Nov 3 2011 Nico Kadel-Garcia <nkadel@nkadel-sl6.localdomain> - 0.68-0.1
- Initial build.

View File

@ -0,0 +1,189 @@
#!/bin/bash
########################################################################
# Testing email delivery
#
# Required nagios email check plugins and zabbix_sender
#
# Author: Sergey Kalinin
# https://nuk-svk.ru
# svk@nuk-svk.ru
########################################################################
# Before, you will must settings variables into .mail_server_FQDN.env files
# and set environment variables:
# BIN_DIR - directory with nagios plugins
# ETC_DIR - directory containing .mail_server_FQDN.env
# Or put bin and var files into /usr/local/bin and /usr/local/etc respectively
#
# Used:
#
# $check_email_send_delivery.sh METHOD MAIL_SERVER
#
# Where METHOD must be like:
#
# "local" - local check
# "incoming" - from external sending to local receiving check
# "outgoing" - from local sending to external receiving check
#
# And MAIL_SERVER - must by FQDN mail server name
########################################################################
if [ -z $1 ]; then
echo "Enter check mode"
exit 1
fi
if [ -z $2 ]; then
echo "Enter mail server address"
exit 1
fi
MAIL_SERVER=$2
ZABBIX_HOST=${ZABBIX_HOST:-${MAIL_SERVER}}
BIN_DIR=${BIN_DIR:-/usr/local/bin}
ETC_DIR=${ETC_DIR:-/usr/local/etc}
RUNNING_ON_DOCKER=${RUNNING_ON_DOCKER:-TRUE}
# Include variables if runing non docker
if [ -z ${RUNNING_ON_DOCKER} ]; then
if [ -e "${ETC_DIR}/.${MAIL_SERVER}.env" ]; then
source "${ETC_DIR}/.${MAIL_SERVER}.env"
else
echo "File ${ETC_DIR}/.${MAIL_SERVER}.env not found. You must setting the variables"
exit 1
fi
fi
ZABBIX_SENDER=${ZABBIX_SENDER:-/usr/bin/zabbix_sender}
# Checking delays setting
WARNING_TIME=${WARNING_TIME:-60}
CRITICAL_TIME=${CRITICAL_TIME:-120}
TIMEOUT=${TIMEOUT:-120}
# Generate message body and subject
SUBJ="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)"
BODY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 64 | head -n 1)
#SUBJ="$(date). SMTP sending checking."
#BODY="SMTP sending checking. $(date)."
case "$1" in
local)
echo "> Local email service check: DOMAIN -> DOMAIN <"
#DELIVERY=$($BIN_DIR/check_email_delivery -H ${MAIL_SERVER} --mailto ${RECEIVER_EMAIL} \
# --mailfrom ${SENDER_EMAIL} --username ${RECEIVER_EMAIL} --password ${RECEIVER_PASSWORD} \
# --body 'Check email delivery')
DELIVERY=$($BIN_DIR/check_email_delivery \
--plugin "$BIN_DIR/check_smtp_send -H ${MAIL_SERVER} \
--mailto ${RECEIVER_EMAIL} --mailfrom ${SENDER_EMAIL} \
--header 'Subject: SMTP sending check' --header 'X-Your-Header: Yes'" \
--plugin "$BIN_DIR/check_imap_receive -H ${MAIL_SERVER} --ssl --port 993 \
--critical ${CRITICAL_TIME} --warning ${WARNING_TIME} --timeout ${TIMEOUT}\
--username ${RECEIVER_EMAIL} --password ${RECEIVER_PASSWORD} \
-s SUBJECT -s 'SMTP sending check' --capture-max 'Homeruns (\d+)' --delete")
SMTP_SEND=$($BIN_DIR/check_smtp_send -H ${MAIL_SERVER} \
--mailto ${RECEIVER_EMAIL} --mailfrom ${SENDER_EMAIL} \
--body 'Homeruns 5' --header 'Subject: SMTP sending check' --header 'X-Your-Header: Yes')
IMAP_RECEIVE=$($BIN_DIR/check_imap_receive -H ${MAIL_SERVER} --ssl --port 993 \
--critical ${CRITICAL_TIME} --warning ${WARNING_TIME} --timeout ${TIMEOUT} \
--username ${RECEIVER_EMAIL} --password ${RECEIVER_PASSWORD} \
-s SUBJECT -s "SMTP sending check" --capture-max "Homeruns (\d+)" --delete)
;;
incoming)
echo "> External email sending local receiving check: GOOGLE -> DOMAIN <"
# # В связи с ограничением провайдеров убрана проверка доставки
# DELIVERY=$($BIN_DIR/check_email_delivery \
# --plugin "$BIN_DIR/check_smtp_send -vvv -H ${EXT_SMTP_SERVER} --port 465 --ssl --username ${EXT_SENDER_EMAIL} \
# --password ${EXT_SENDER_PASSWORD} --mailto ${RECEIVER_EMAIL} --mailfrom ${EXT_SENDER_EMAIL} \
# --body "${BODY}" --header \"Subject: ${SUBJ}\" --header 'X-Your-Header: Yes'" \
# --plugin "$BIN_DIR/check_imap_receive -H ${MAIL_SERVER} --port 993 --ssl \
# --username ${RECEIVER_EMAIL} --password ${RECEIVER_PASSWORD} \
# -s SUBJECT -s "${SUBJ}" --capture-max \"${BODY}\" --nodelete-captured")
# --critical ${CRITICAL_TIME} --warning ${WARNING_TIME} --timeout ${TIMEOUT}\
SMTP_SEND=$($BIN_DIR/check_smtp_send -vvv -H ${EXT_SMTP_SERVER} --port 465 --ssl --username ${EXT_SENDER_EMAIL} \
--password ${EXT_SENDER_PASSWORD} --mailto ${RECEIVER_EMAIL} --mailfrom ${EXT_SENDER_EMAIL} \
--body "${BODY}" --header "Subject: ${SUBJ}" --header 'X-Your-Header: Yes')
IMAP_RECEIVE=$($BIN_DIR/check_imap_receive -H ${MAIL_SERVER} --ssl --port 993 \
--critical ${CRITICAL_TIME} --warning ${WARNING_TIME} --timeout ${TIMEOUT} \
--username ${RECEIVER_EMAIL} --password ${RECEIVER_PASSWORD} \
-s SUBJECT -s "${SUBJ}" --capture-max "${BODY}" --delete)
;;
outgoing)
echo "> Local email sending external receiving check: DOMAIN -> GOOGLE <"
DELIVERY=$($BIN_DIR/check_email_delivery \
--plugin "$BIN_DIR/check_smtp_send -H ${MAIL_SERVER}\
--mailto ${EXT_RECEIVER_EMAIL} --mailfrom ${SENDER_EMAIL} \
--body \"${BODY}\" --header \"Subject: ${SUBJ}\" --header 'X-Your-Header: Yes'" \
--plugin "$BIN_DIR/check_imap_receive -H ${EXT_IMAP_SERVER} --ssl --username ${EXT_RECEIVER_EMAIL} \
--password ${EXT_RECEIVER_PASSWORD} -s SUBJECT -s \"${SUBJ}\" --capture-max \"${BODY}\" \
--delete")
SMTP_SEND=$($BIN_DIR/check_smtp_send -H ${MAIL_SERVER}\
--mailto ${EXT_RECEIVER_EMAIL} --mailfrom ${SENDER_EMAIL} \
--body "${BODY}" --header "Subject: ${SUBJ}" --header 'X-Your-Header: Yes')
IMAP_RECEIVE=$($BIN_DIR/check_imap_receive -H ${EXT_IMAP_SERVER} --ssl --port 993 \
--critical ${CRITICAL_TIME} --warning ${WARNING_TIME} --timeout ${TIMEOUT} \
--username ${EXT_RECEIVER_EMAIL} --password ${EXT_RECEIVER_PASSWORD} \
-s SUBJECT -s "${SUBJ}" --capture-max "${BODY}" --delete)
;;
esac
#--ssl-ca-file ya.pem
DELIVERY_STATUS=$(echo "${DELIVERY}" | awk '{print $3}')
DELIVERY_TIME=$(echo "${DELIVERY}" | awk 'match($0,/delay=[0-9]+s/) {print substr($0,RSTART+6,RLENGTH-6-1)}')
DELIVERY_ELAPSED_TIME=$(echo "${DELIVERY}" | awk 'match($0,/elapsed=[0-9]+s/) {print substr($0,RSTART+8,RLENGTH-8-1)}')
echo "${DELIVERY}"
echo "${DELIVERY_STATUS}"
echo "${DELIVERY_TIME}"
echo "${DELIVERY_ELAPSED_TIME}"
SMTP_SEND_STATUS=$(echo ${SMTP_SEND} | awk '{print $3}')
SMTP_SEND_ELAPSED_TIME=$(echo ${SMTP_SEND} | awk 'match($0,/elapsed=[0-9]+s/) { print substr($0,RSTART+8,RLENGTH-8-1)}')
echo "${SMTP_SEND}"
echo "${SMTP_SEND_STATUS}"
echo "${SMTP_SEND_ELAPSED_TIME}"
IMAP_RECEIVE_STATUS=$(echo ${IMAP_RECEIVE} | awk '{print $3}')
IMAP_RECEIVE_ELAPSED_TIME=$(echo ${IMAP_RECEIVE} | awk 'match($0,/elapsed=[0-9]+s/) { print substr($0,RSTART+8,RLENGTH-8-1)}')
echo "${IMAP_RECEIVE}"
echo "${IMAP_RECEIVE_STATUS}"
echo "${IMAP_RECEIVE_ELAPSED_TIME}"
if [ $DELIVERY_STATUS ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.delivery.${1}.status -o $DELIVERY_STATUS
fi
if [ $DELIVERY_TIME ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.delivery.${1}.delay -o $DELIVERY_TIME
fi
if [ $DELIVERY_ELAPSED_TIME ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.delivery.${1}.elapsed -o $DELIVERY_ELAPSED_TIME
fi
if [ $SMTP_SEND_STATUS ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.smtp_send.${1}.status -o $SMTP_SEND_STATUS
fi
if [ $SMTP_SEND_ELAPSED_TIME ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.smtp_send.${1}.elapsed -o $SMTP_SEND_ELAPSED_TIME
fi
if [ $IMAP_RECEIVE_STATUS ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.imap_receive.${1}.status -o $IMAP_RECEIVE_STATUS
fi
if [ $IMAP_RECEIVE_ELAPSED_TIME ]; then
${ZABBIX_SENDER} -c /etc/zabbix/zabbix_agentd.conf -s "${ZABBIX_HOST}" -k email.imap_receive.${1}.elapsed -o $IMAP_RECEIVE_ELAPSED_TIME
fi
exit 0

View File

@ -0,0 +1,22 @@
version: '3'
services:
email_delivery_check_mail:
image: email_delivery_check
env_file: .mail1.example.com.env
environment:
- MAIL_SERVER=mail1.example.com
- RUNNING_ON_DOCKER=TRUE
restart: always
build:
context: ./
email_delivery_check_mail2:
image: email_delivery_check
env_file: .mail1.example.com.env
environment:
- MAIL_SERVER=mail2.example.com
- RUNNING_ON_DOCKER=TRUE
restart: always
build:
context: ./

View File

@ -0,0 +1,7 @@
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh local mail.example.com
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh incoming mail.example.com
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh outgoing mail.example.com
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh local mail2.example.com
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh incoming mail2.example.com
*/5 * * * * root /usr/local/bin/check_email_send_delivery.sh outgoing mail2.example.com

14
check_email_delivery/run.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/bash
# Run service
BIN_DIR=${BIN_DIR:-/usr/local/bin}
ETC_DIR=${ETC_DIR:-/usr/local/etc}
LIB_DIR=${LIB_DIR:-/usr/local/lib}
echo "Creating host into zabbix"
${BIN_DIR}/zabbix_create_host.sh
${BIN_DIR}/check_email_send_delivery.sh local ${MAIL_SERVER}
${BIN_DIR}/check_email_send_delivery.sh incoming ${MAIL_SERVER}
${BIN_DIR}/check_email_send_delivery.sh outgoing ${MAIL_SERVER}
sleep 300

38
check_email_delivery/sample.env Executable file
View File

@ -0,0 +1,38 @@
# Local sender settings
SENDER_EMAIL=delivery_speed@example.com
SENDER_PASSWORD=some-password
# Local receiver settings
RECEIVER_EMAIL=delivery_speed@example.com
RECEIVER_PASSWORD=some-password
# External IMAP ans SMTP servers
EXT_SMTP_SERVER=smtp.gmail.com
EXT_IMAP_SERVER=imap.gmail.com
# External sender settings
EXT_SENDER_EMAIL=external@gmail.com
EXT_SENDER_PASSWORD=some-password
# External receiver settings
EXT_RECEIVER_EMAIL=external@gmail.com
EXT_RECEIVER_PASSWORD=some-password
# Zabbix setting
ZABBIX_HOST=Email_delivery_test_for_mail
ZABBIX_USER=zabbix-user
ZABBIX_PASSWORD=zabbix-password
ZABBIX_TEMPLATE_NAME=Template_Email_Delivery_Check
### Systems variable with default values
### uncoment if you whant changes default setting
# BIN_DIR=/usr/local/bin
# ETC_DIR=/usr/local/etc
# ZABBIX_SENDER=/usr/bin/zabbix_sender
# Checking delays setting
# WARNING_TIME=60
# CRITICAL_TIME=120
# TIMEOUT=120

View File

@ -0,0 +1,216 @@
#!/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:-"Test Virtual Host"}
ZABBIX_TEMPLATE_NAME=${ZABBIX_TEMPLATE_NAME:-"Some_Template"}
#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
# Проверяем наличие узла если он есть возвращаем ID если нет - создаем
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
# Проверяем наличие шаблона если он есть возвращаем ID если нет - создаем
if [ -z "$TEMPLATE_ID" ]; then
get_template
fi
# Проверяем наличие группы узлов если она есть возвращаем ID если нет - создаем
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

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
}

View File

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

View File

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

View File

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

View File

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

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
}

View File

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

View File

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

File diff suppressed because it is too large Load Diff

3
es-monitoring/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.env
main
es-monitoring

17
es-monitoring/Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM golang:alpine AS build
RUN apk --no-cache add gcc g++ make git
WORKDIR /go/src/app
COPY . .
RUN go get ./...
RUN GOOS=linux go build -ldflags="-s -w" -o ./bin/es-monitoring ./es-monitoring.go
FROM alpine:3.9
#RUN apk --no-cache add ca-certificates
WORKDIR /usr/bin
COPY --from=build /go/src/app/bin /go/bin
COPY cronjobs /etc/crontabs/root
# start crond with log level 8 in foreground, output to stderr
CMD ["crond", "-f", "-d", "8"]
#ENTRYPOINT /go/bin/es-monitor

69
es-monitoring/README.md Normal file
View File

@ -0,0 +1,69 @@
# Es Monitoring
Мониторинг индексов Elasticsearch в Zabbix.
Программа получает список имён индексов без цифровой части, т.е. так называемые pattern. К примеру если индекс "filebeat-01.01.2020" то использоваться будет имя (тут и далее под индексом подразумевается паттерн) "filebeat". Данные имена добавляются в zabbix через автообнаружение (предварительно требуется к узлу подключить приложенный шаблон).
На основе списка имен индексов (данные будут взяты из последнего индекса по времени попадающего под шаблон имени) можно получать количество записей за временной промежуток (задаётся с командой строки в часах, по умолчанию равен 6 часам).
Программу можно запускать как в консоли так и в docker-контейнере.
# Режимы работы
- operation - задаёт тип выполняемой операции
* es-cluster-info - вывод информации о кластере (версии)
* es-get-indices - вывод списка индексов
* es-indices-discover - вывод списка индексов ввиде JSON для отправки в zabbix
* es-records-count - подсчёт количества данных по всем индексам
* es-index-records-count - подсчет записей по одному индексу (используется совместно с -index-name)
- index-name - имя индекса (паттерн)
- timerange - временной промежуток в часах
- zabbix-send - при указании данной опции результат коамнды будет отправлен в заббикс
- help - вывод краткой помощи
# использование
Для работы используются переменные окружения:
- ELASTICSEARCH_URL="https://__USER__:__PASSWORD__@elastic:9200"
- ZABBIX_SERVER=https://zabbix2
- ZABBIX_HOST=elastic
- ZABBIX_USERNAME=zabbix_user
- ZABBIX_PASSWORD=somepass
## Пример команды
Подсчет количества записей по всем индексам и отправка в заббикс:
```
es-monitoring -operation es-records-count -timerange 1 -zabbix-send
```
Вывод списка индексов для zabbix
```
es-monitoring -operation es-indices-discover -zabbix-send
```
Подсчет количества записей для индексов filebeat* за 12 часов (данные будут взяты из последнего индекса по времени)
```
es-monitoring -operation es-index-records-count -index-name filebeat -timerange 12
```
# Краткая помощь по программе
```
Usage of ./es-monitor:
-indexname string
Elasticsearch index name pattern, (like "filebeat")
-operation string
Opertation type, must be:
es-cluster-info - ES Cluster information (version e.t.c)
es-get-indices - geting all index
es-indices-discover - getting es index pattern list
es-records-count - getting the number of records for a time range for all index pattern
es-index-records-count - getting records count for one index (used with -indexname option (default "es-cluster-info")
-timerange int
Elasticsearch time range for records count into hours (default 6)
-zabbix-send
Send metrics or discovery data into zabbix
```

2
es-monitoring/cronjobs Normal file
View File

@ -0,0 +1,2 @@
*/10 * * * * /go/bin/es-monitoring -operation es-records-count -timerange 1 -zabbix-send >> /var/log/es-monitoring.log 2>&1
0 * * * * /go/bin/es-monitoring -operation es-indices-discover -zabbix-send >> /var/log/es-monitoring.log 2>&1

View File

@ -0,0 +1,19 @@
version: '3'
services:
es_monitoring:
image: $IMAGE_PATH/es_monitoring:latest
environment:
- ZABBIX_USER=${ZABBIX_USER}
- ZABBIX_PASSWORD=${ZABBIX_PASSWORD}
- ZABBIX_HOST=elastic
- ZABBIX_SERVER=zabbix
- ZABBIX_PORT=10051
- ELASTICSEARCH_URL=${ELASTICSEARCH_URL}
restart: always
build:
context: .
logging:
options:
max-size: "10m"
max-file: "5"

View File

@ -0,0 +1,405 @@
//------------------------------------------------------------------------------
// Getting and monitoring Elasticsearch indices and send the metrics into zabbix
//-------------------------------------------------------------------------------
// Author: Sergey Kalinin
// e-mail: svk@nuk-svk.ru
// website: https://nuk-svk.ru
// Git repos: https://git.nuk-svk.ru
//-------------------------------------------------------------------------------
// Require:
// github.com/adubkov/go-zabbix
// github.com/elastic/go-elasticsearch
//-------------------------------------------------------------------------------
// ZABBIX_SERVER="zabbix"
// ZABBIX_PORT="10051"
// ZABBIX_HOST="elastic cluster"
// ELASTICSEARCH_URL="https://user:pass@elastic:9200"
//-------------------------------------------------------------------------------
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/adubkov/go-zabbix"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
)
type json_records struct {
INDEX string
RECORD_COUNT int
}
// Определяем входит ли строка в slice
func StringContains(a []string, x string) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
func EsSearch(index_name string, es_request_time_range int) int {
var (
r map[string]interface{}
)
request_time_range := "now-" + strconv.Itoa(es_request_time_range) + "h"
cfg := elasticsearch.Config{
// Addresses: []string{
// "http://localhost:9200",
// "http://localhost:9201",
// },
// Username: "foo",
// Password: "bar",
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 60 * time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
TLSClientConfig: &tls.Config{
MaxVersion: tls.VersionTLS11,
InsecureSkipVerify: true,
},
},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
// Check response status
if res.IsError() {
log.Fatalf("Error: %s", res.String())
}
var buf bytes.Buffer
query := map[string]interface{}{
"query": map[string]interface{}{
"range": map[string]interface{}{
"@timestamp": map[string]interface{}{
// "gt": "now-1h",
"gt": request_time_range,
},
// "match": map[string]interface{}{
// "host": "10.250.1.212",
},
},
"size": 1,
"sort": map[string]interface{}{
"@timestamp": map[string]interface{}{
"order": "desc",
},
},
}
if err := json.NewEncoder(&buf).Encode(query); err != nil {
log.Fatalf("Error encoding query: %s", err)
}
// Perform the search request.
res, err = es.Search(
es.Search.WithContext(context.Background()),
es.Search.WithIndex(index_name+"*"),
es.Search.WithBody(&buf),
es.Search.WithTrackTotalHits(true),
es.Search.WithPretty(),
)
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
if res.IsError() {
var e map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
} else {
// Print the response status and error information.
log.Fatalf("[%s] %s: %s",
res.Status(),
e["error"].(map[string]interface{})["type"],
e["error"].(map[string]interface{})["reason"],
)
}
}
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
// Вывод статуса, количество выбранных записей и времени запроса
hits := int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64))
return hits
}
func EsIndexDiscover(es_index_list []string) string {
result_discovery_json := string("{\"data\": [")
for _, value := range es_index_list {
// result_discovery_json = result_discovery_json + "{\"{#INDEX}\":\"" + value + "\",\"{#ITEM_TYPE}\":\"Records count\"" + "},"
result_discovery_json = result_discovery_json + "{\"{#INDEX}\":\"" + value + "\"" + "},"
}
result_discovery_json = strings.TrimRight(result_discovery_json, ",") + "]}"
// fmt.Println(result_discovery_json)
return (result_discovery_json)
}
func EsIndexRecordsCount(es_index_list []string, es_request_time_range int) {
// fmt.Println(es_request_time_range)
result_index := make(map[int]json_records)
j := int(0)
for _, value := range es_index_list {
result_index[j] = json_records{value, EsSearch(value, es_request_time_range)}
j++
}
log.Println(result_index)
}
func EsClusterInfo(es *elasticsearch.Client) {
var (
r map[string]interface{}
)
// 1. Get cluster info
res, err := es.Info()
if err != nil {
log.Fatalf("Error getting response: %s", err)
}
defer res.Body.Close()
// Check response status
if res.IsError() {
log.Fatalf("Error: %s", res.String())
}
// Deserialize the response into a map.
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
// Print client and server version numbers.
fmt.Printf("Client: %s\n", elasticsearch.Version)
fmt.Printf("Client: %s\n", elasticsearch.Version)
fmt.Printf("Server: %s\n", r["version"].(map[string]interface{})["number"])
}
func EsIndexFieldExists(es *elasticsearch.Client, index_name string, field_name string) bool {
// Check if the filed exists into index
var (
fields_request map[string]interface{}
fields []string
indices []string
field_exists bool
)
fields = append(fields, field_name)
indices = append(indices, index_name)
req := esapi.FieldCapsRequest{
// Index: []string{},
Index: indices,
Fields: fields,
}
res, err := req.Do(context.Background(), es)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
if err := json.NewDecoder(res.Body).Decode(&fields_request); err != nil {
log.Fatalf("->Error parsing the response body: %s", err)
}
for i, f := range fields_request {
if i == "fields" {
// if f.(map[string]interface{})[`@timestamp`] == nil {
if f.(map[string]interface{})[field_name] == nil {
field_exists = false
} else {
field_exists = true
}
}
}
return (field_exists)
}
func EsGetIndices(es *elasticsearch.Client) []string {
//Get indices list
var (
index_request []map[string]interface{}
es_index_list []string
)
req := esapi.CatIndicesRequest{
// Index: []string{},
Format: "JSON",
// ExpandWildcards,
}
res, err := req.Do(context.Background(), es)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
if err := json.NewDecoder(res.Body).Decode(&index_request); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
for _, hit := range index_request {
m := regexp.MustCompile("-[0-9]")
// позиция вхождения регулярки в имени индекса
i := m.FindStringIndex(hit["index"].(string))
// наименование индекса
index_name := hit["index"].(string)
// Checking the @timestamp field exists
if !EsIndexFieldExists(es, index_name, `@timestamp`) {
continue
// fmt.Println(EsIndexFieldExists(es, index_name))
}
// Итоговое наименование индекса
var index_name_short string
// Исключаем индексы от кибаны (.kibana-*) и обрезаем цифры (даты и версии)
if !strings.HasPrefix(index_name, ".") {
if i != nil {
index_name_short = strings.TrimSpace(index_name[0:i[0]])
} else {
index_name_short = strings.TrimSpace(index_name)
}
if !StringContains(es_index_list, index_name_short) {
es_index_list = append(es_index_list, index_name_short)
}
}
}
return (es_index_list)
}
func ZabbixSender(zabbix_host string, metric_name string, metric_value string) bool {
var (
metrics []*zabbix.Metric
zabbix_port int
err error
)
zabbix_server := os.Getenv("ZABBIX_SERVER")
// Read and checkin zabbix server and port
if zabbix_server == "" {
log.Println("Login error: make sure environment variables `ZABBIX_SERVER` are defined")
os.Exit(1)
}
if os.Getenv("ZABBIX_PORT") == "" {
log.Println("Login error: make sure environment variables `ZABBIX_PORT` are defined")
os.Exit(1)
}
if zabbix_port, err = strconv.Atoi(os.Getenv("ZABBIX_PORT")); err != nil {
log.Println(zabbix_port, "Zabbix port value error")
}
metrics = append(metrics, zabbix.NewMetric(zabbix_host, metric_name, metric_value, time.Now().Unix()))
metrics = append(metrics, zabbix.NewMetric(zabbix_host, "status", "OK"))
// Create instance of Packet class
packet := zabbix.NewPacket(metrics)
// fmt.Println(zabbix_host, metric_name, metric_value, metrics)
// Send packet to zabbix
z := zabbix.NewSender(zabbix_server, zabbix_port)
res, err := z.Send(packet)
log.Println(string(res))
return true
}
//---------------------------------------------------------------------------
func main() {
var (
operation string
es_index_name string
es_request_time_range int
zabbix_send bool
// zabbix_port int
)
flag.StringVar(&es_index_name, "indexname", "", "Elasticsearch index name pattern, (like \"filebeat\")")
flag.IntVar(&es_request_time_range, "timerange", 6, "Elasticsearch time range for records count into hours")
flag.BoolVar(&zabbix_send, "zabbix-send", false, "Send metrics or discovery data into zabbix")
flag.StringVar(&operation, "operation", "es-cluster-info", "Opertation type, must be:\n\tes-cluster-info - ES Cluster information (version e.t.c)\n\tes-get-indices - geting all index\n\tes-indices-discover - getting es index pattern list\n\tes-records-count - getting the number of records for a time range for all index pattern\n\tes-index-records-count - getting records count for one index (used with -indexname option")
flag.Parse()
zabbix_host := os.Getenv("ZABBIX_HOST")
if zabbix_host == "" {
fmt.Println("Send error: make sure environment variables `ZABBIX_HOST`")
os.Exit(1)
}
// if es_request_time_range > 24 {
// log.Println("Error: Time range must be a number between 1 and 24")
// os.Exit(1)
// }
cfg := elasticsearch.Config{
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 30 * time.Second,
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext,
TLSClientConfig: &tls.Config{
MaxVersion: tls.VersionTLS11,
InsecureSkipVerify: true,
},
},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
// fmt.Println(operation)
switch operation {
case "es-cluster-info":
EsClusterInfo(es)
case "es-get-indices":
// fmt.Println(operation)
for _, index := range EsGetIndices(es) {
fmt.Println(index)
}
case "es-indices-discover":
result_discovery_json := EsIndexDiscover(EsGetIndices(es))
// fmt.Println(zabbix_send)
if zabbix_send == true {
ZabbixSender(zabbix_host, "indices", result_discovery_json)
}
fmt.Println(result_discovery_json)
case "es-records-count":
// records count for all indices
// EsIndexRecordsCount(EsGetIndices(es), es_request_time_range)
result_index := make(map[int]json_records)
j := int(0)
for _, es_index_name := range EsGetIndices(es) {
result := EsSearch(es_index_name, es_request_time_range)
result_index[j] = json_records{es_index_name, result}
log.Println("ES index name:", es_index_name, "; Query time period:", es_request_time_range, "; Records count:", result)
if zabbix_send == true {
ZabbixSender(zabbix_host, `indices.records_count[`+es_index_name+`]`, strconv.Itoa(result))
ZabbixSender(zabbix_host, `indices.records_count_time_range[`+es_index_name+`]`, strconv.Itoa(es_request_time_range))
}
j++
}
case "es-index-records-count":
// records count for one index
result := EsSearch(es_index_name, es_request_time_range)
if zabbix_send == true {
ZabbixSender(zabbix_host, `indices.records_count[`+es_index_name+`]`, strconv.Itoa(result))
ZabbixSender(zabbix_host, `indices.records_count_time_range[`+es_index_name+`]`, strconv.Itoa(es_request_time_range))
}
log.Println("ES index name:", es_index_name, "; Query time period:", es_request_time_range, "; Records count:", result)
}
}

12
es-monitoring/go.mod Normal file
View File

@ -0,0 +1,12 @@
module my-elasticsearch-app
go 1.16
require github.com/elastic/go-elasticsearch/v7 v7.5.1-0.20210322101442-a3e161131102
require (
github.com/adubkov/go-zabbix v0.0.0-20170118040903-3c6a95ec4fdc // indirect
github.com/cavaliercoder/go-zabbix v0.0.0-20210304010121-96120c17dd42 // indirect
github.com/nixys/nxs-go-zabbix/v5 v5.0.0
github.com/rday/zabbix v0.0.0-20170517233925-1cf60ccd42f9 // indirect
)

14
es-monitoring/go.sum Normal file
View File

@ -0,0 +1,14 @@
github.com/adubkov/go-zabbix v0.0.0-20170118040903-3c6a95ec4fdc h1:gqqI4ZPa7uwK+gX9Zgk2AweAh+2dX0FpETcXTsA2TrE=
github.com/adubkov/go-zabbix v0.0.0-20170118040903-3c6a95ec4fdc/go.mod h1:ihDXRSVen590YHlXIrv00CcmRrL6pUho/Iwm3ZmM8n8=
github.com/cavaliercoder/go-zabbix v0.0.0-20210304010121-96120c17dd42 h1:S+MAp8YOH/TkyOTHa1/z/reraTs7fJL0xBOx5+3bA78=
github.com/cavaliercoder/go-zabbix v0.0.0-20210304010121-96120c17dd42/go.mod h1:o9iZ0ep18zjkTdG1yoCmBZSMAWo2qUXVMxqmEl+6GLo=
github.com/elastic/go-elasticsearch v0.0.0 h1:Pd5fqOuBxKxv83b0+xOAJDAkziWYwFinWnBO0y+TZaA=
github.com/elastic/go-elasticsearch v0.0.0/go.mod h1:TkBSJBuTyFdBnrNqoPc54FN0vKf5c04IdM4zuStJ7xg=
github.com/elastic/go-elasticsearch/v7 v7.5.1-0.20210322101442-a3e161131102 h1:o4HAbzLv9EOWc6ue8fyB00AcE78Y3fp8FD9RYy0z73M=
github.com/elastic/go-elasticsearch/v7 v7.5.1-0.20210322101442-a3e161131102/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4=
github.com/mitchellh/mapstructure v1.3.0 h1:iDwIio/3gk2QtLLEsqU5lInaMzos0hDTz8a6lazSFVw=
github.com/mitchellh/mapstructure v1.3.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/nixys/nxs-go-zabbix/v5 v5.0.0 h1:AvVNPs/w2xSampQn25KnvNOx49O9mE5KuIlLrSTXpnE=
github.com/nixys/nxs-go-zabbix/v5 v5.0.0/go.mod h1:9R4cq2L8wHvVAz0ZfNIvzyXRUGCsrJOd7HvWiRoz6TI=
github.com/rday/zabbix v0.0.0-20170517233925-1cf60ccd42f9 h1:ARUuqpY5LjSR4//P6TolxJP81zjO+qNuOlEVD4mvIfs=
github.com/rday/zabbix v0.0.0-20170517233925-1cf60ccd42f9/go.mod h1:IIFS/h+mpikvp6WVUQwg9fO8IlGy7q3LE1wt3MeWhvg=

View File

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>5.0</version>
<date>2021-04-05T12:40:38Z</date>
<groups>
<group>
<name>Elastic cluster</name>
</group>
</groups>
<templates>
<template>
<template>Template Elasticsearch Indices Monitoring</template>
<name>Template Elasticsearch Indices Monitoring</name>
<description>Template for monitoring the elasticsearch index.</description>
<groups>
<group>
<name>Elastic cluster</name>
</group>
</groups>
<applications>
<application>
<name>ES indices</name>
</application>
</applications>
<discovery_rules>
<discovery_rule>
<name>Index discovery</name>
<type>TRAP</type>
<key>indices</key>
<delay>0</delay>
<item_prototypes>
<item_prototype>
<name>{#INDEX} records count</name>
<type>TRAP</type>
<key>indices.records_count[{#INDEX}]</key>
<delay>0</delay>
<application_prototypes>
<application_prototype>
<name>ES index &quot;{#INDEX}&quot;</name>
</application_prototype>
</application_prototypes>
<trigger_prototypes>
<trigger_prototype>
<expression>{last()}=0</expression>
<name>{HOSTNAME}. Отсутствуют записи в индексе {#INDEX}</name>
<priority>WARNING</priority>
<manual_close>YES</manual_close>
</trigger_prototype>
</trigger_prototypes>
</item_prototype>
<item_prototype>
<name>{#INDEX} records count time range</name>
<type>TRAP</type>
<key>indices.records_count_time_range[{#INDEX}]</key>
<delay>0</delay>
<application_prototypes>
<application_prototype>
<name>ES index &quot;{#INDEX}&quot;</name>
</application_prototype>
</application_prototypes>
</item_prototype>
</item_prototypes>
</discovery_rule>
</discovery_rules>
</template>
</templates>
</zabbix_export>

View File

@ -0,0 +1,13 @@
#!/bin/bash
case "$2" in
available)
echo $(/bin/df | /bin/grep "$1"| /usr/bin/awk '{print $4}')
;;
usage)
echo $(/bin/df | /bin/grep "$1"| /usr/bin/awk '{print $3}')
;;
percent)
echo $(/bin/df | /bin/grep "$1"| /usr/bin/awk '{print $5}' | tr -d "%")
;;
esac

View File

@ -0,0 +1,3 @@
UserParameter=lxc.filesystem.usage[*],/usr/local/bin/get_fs_status.sh "$1" usage
UserParameter=lxc.filesystem.available[*],/usr/local/bin/get_fs_status.sh "$1" available
UserParameter=lxc.filesystem.usage.percent[*],/usr/local/bin/get_fs_status.sh "$1" percent

35
zabbix_api_use/README.md Executable file
View File

@ -0,0 +1,35 @@
## Работа с zabbix REST API
## Описание
Набор скриптов для создания узла в заббикс через REST API. Создан по мотивам https://www.reddit.com/r/zabbix/comments/bhdhgq/zabbix_api_example_using_just_bash_curl_and_jq/
- добавляет узел
- добавляет шаблон
- добавляет группу узлов
- приписывает шаблон и группу к узлу
В состав сервиса входит:
- zabbix_create_host.sh - позволяет создать в zabbix группу узлов, шаблон, узел. В случае если объект уже есть, то будет получен его идентификатор. Используется Zabbix JSON RPC.
- zabbix_jrpc_files - каталог содержит JSON-файлы с описанием процедур по взаимодействия с zabbix
- zabbix_templates - шаблоны zabbix
## Использование
Предварительно требуется изменить значения переменных окружения (если необходимо). Список переменных со значениями по умолчанию:
- BIN_DIR=/usr/local/bin
- ETC_DIR=/usr/local/etc
- LIB_DIR=/usr/local/lib
- ZABBIX_SERVER='http://zabbix.example.com'
- ZABBIX_USER=
- ZABBIX_PASSWORD=
- ZABBIX_HOST_GROUP:-'Virtual Hosts'
- ZABBIX_HOST "Some my host"
- ZABBIX_TEMPLATE_NAME="Template_DNS_Check"
Запуск команды:
```./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

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
}

View File

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

View File

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

View File

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

View File

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

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
}

View File

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

View File

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