Monitorggio di record MX con Nagios
Jump to navigation
Jump to search
- Il plugin utilizzato è il seguente:
sudo mkdir -p /usr/local/lib/nagios/plugins/
cat | sudo tee /usr/local/lib/nagios/plugins/check_mx > /dev/null <<'EOFile'
#!/usr/bin/env python
###############################################################################
# Nagios plugin to check if an host is configured as mx record for a domain
#
# Notes
# - You need dnspython installed:
# sudo apt-get install python-dnspython
#
###############################################################################
__author__ = 'Gabriele Vivinetto'
__version__= 0.1
from optparse import OptionParser, OptionGroup
import logging as log
## These will override any args passed to the script normally.
## Comment out after testing.
#testargs = '--help'
#testargs = '--version'
#testargs = '-vvv'
def main():
""" Main plugin logic goes here """
## Parse command-line arguments
args, args2 = parse_args()
## Options variable are accessibles as args.variablename
## Uncomment to test logging levels against verbosity settings
# log.debug('debug message')
# log.info('info message')
# log.warning('warning message')
# log.error('error message')
# log.critical('critical message')
# log.fatal('fatal message')
import dns.resolver
# The domain name to check
domain = args.domain
log.info("Testing domain: " + domain )
myResolver = dns.resolver.Resolver()
## Find The ip address to check from args.hostIp and put into hostIp
## Maybe the hostname resolves to multiple IPs
try:
hostIpAddresses = dns.resolver.query(args.hostIp,'A')
except dns.resolver.NXDOMAIN:
gtfo(3,"UNKNOWN No such hostname %s" % args.hostIp)
except dns.resolver.Timeout:
gtfo(3,"UNKNOWN Timed out while resolving %s" % args.hostIp)
except dns.exception.DNSException:
gtfo(3, "UNKNOWN Unknown error")
## Find all the MX Records
try:
mxRecords = myResolver.query(domain, 'MX')
except dns.resolver.NXDOMAIN:
gtfo(3,"UNKNOWN No such domain %s" % domain)
except dns.resolver.Timeout:
gtfo(3,"UNKNOWN Timed out while resolving %s" % domain)
except dns.exception.DNSException:
gtfo(3, "UNKNOWN Unknown error")
for ip in hostIpAddresses :
hostIp = ip.to_text()
log.info("Testing HOST IP " + hostIp )
for record in mxRecords :
mx = record.exchange.to_text()
log.info("Testing MX " + mx )
try:
ipAddress = dns.resolver.query(mx,'A')
except dns.resolver.NXDOMAIN:
gtfo(3,"UNKNOWN No such domain %s" % mx)
except dns.resolver.Timeout:
gtfo(3,"UNKNOWN Timed out while resolving %s" % mx)
except dns.exception.DNSException:
gtfo(3, "UNKNOWN Unknown error")
for ip in ipAddress :
indirizzo = ip.to_text()
if hostIp == indirizzo:
log.info( hostIp + "=" + indirizzo)
gtfo(0,"OK Your host " + args.hostIp + " with ip " + indirizzo + " is MX for domain " + domain)
gtfo(2,"CRITICAL Your host " + hostIp + " is NOT an MX record for domain " + domain)
def parse_args():
""" Parse command-line arguments """
parser = OptionParser(usage='usage: %prog [-v|vv|vvv] [options]',
version='{0}: v.{1} by {2}'.format('%prog', __version__, __author__))
## Verbosity (want this first, so it's right after --help and --version)
parser.add_option('-v', help='Set verbosity level',
action='count', default=0, dest='v')
## CLI arguments specific to this script
#group = OptionGroup(parser,'Plugin Options')
#group.add_option('-x', '--extra', help='Your option here',
# default=None)
#parser.add_option_group(group)
parser.add_option('-H', '--hostname', help='The hostname/ip to check if its mx record',
dest='hostIp', metavar='##')
parser.add_option('-d', '--domain', help='The domain name to check mx records for.',
dest='domain', metavar='##')
## Common CLI arguments
#parser.add_option('-c', '--critical', help='Set the critical threshold. Default: %(default)s',
# default=97, type=float, dest='crit', metavar='##')
#parser.add_option('-w', '--warning', help='Set the warning threshold. Default: %(default)s',
# default=95, type=float, dest='warn', metavar='##')
## Try to parse based on the testargs variable. If it doesn't exist, use args
try:
args, args2 = parser.parse_args(testargs.split())
except NameError:
args, args2 = parser.parse_args()
## Set the logging level based on the -v arg
log.getLogger().setLevel([log.ERROR, log.WARN, log.INFO, log.DEBUG][args.v])
log.debug('Parsed arguments: {0}'.format(args))
log.debug('Other arguments: {0}'.format(args2))
return args, args2
def gtfo(exitcode, message=''):
""" Exit gracefully with exitcode and (optional) message """
log.debug('Exiting with status {0}. Message: {1}'.format(exitcode, message))
if message:
print(message)
exit(exitcode)
if __name__ == '__main__':
## Initialize logging before hitting main, in case we need extra debuggability
log.basicConfig(level=log.DEBUG, format='%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
main()
EOFile
sudo chmod +x /usr/local/lib/nagios/plugins/check_mx
- Definire i check commands:
# check-mx
define command{
command_name check-mx
command_line /usr/local/lib/nagios/plugins/check_mx -H $HOSTNAME$ -d $ARG1$
}
# check-mx-host
define command{
command_name check-mx-host
command_line /usr/local/lib/nagios/plugins/check_mx -H $ARG1$ -d $ARG2$
}
- Per testare se l'host oggetto del check è un record mx per il dominio example.com:
define service{
use generic-service
host_name server.example.com
service_description MX-EXAMPLED.COM
check_command check-mx!example.com
}
- Per testare se un host specifico otherserver.example.com è un record mx per il dominio example.com:
define service{
use generic-service
host_name server.example.com
service_description MX-EXAMPLE.COM
check_command check-mx!otherserver.example.com!exampledomain.com
}