Monkey Albino

Linux altar53.supremepanel53.com 4.18.0-553.8.1.lve.el8.x86_64 #1 SMP Thu Jul 4 16:24:39 UTC 2024 x86_64
/ lib64/ nagios/ plugins/

//lib64/nagios/plugins/check_am_ntp

#!/usr/bin/env python
"""
teh (3.10.2014)
"""

import sys
import subprocess
import re
import shlex
import math

num_arg = len(sys.argv)

if num_arg < 4:
	print 'Usage: ' + sys.argv[0] + ' <warning threshold> <critical threshold> <server(s)/pool(s) to query>'
	sys.exit(3)

try:
	warning_threshold = float(sys.argv[1])
	critical_threshold = float(sys.argv[2])
except:
	print 'Error: warning or critical threshold is not a number.'
	sys.exit(3)

servers = ''

if warning_threshold >= critical_threshold:
	print 'Error: warning threshold is bigger or equal to critical threshold. That\'s wrong.'
	sys.exit(3)

ip_hostname_regex = "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$|^([a-zA-Z0-9\-]+\.){1,16}[a-zA-Z]{2,}$"
valid_server = re.compile(ip_hostname_regex)

for index in range(num_arg):
	if index > 2:
		arg = sys.argv[index]
	
		if not valid_server.match(arg):
			print 'Error: invalid server syntax.'
			sys.exit(3)
		
		servers = servers + ' ' + arg

servers = servers.strip()
ntp_cmd = shlex.split('ntpdate -q ' + servers)

ntp = subprocess.Popen(ntp_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
ntp_output = ntp.communicate()[0]
ntp_rc = ntp.returncode

if ntp_rc != 0: 
	print 'Error executing ntpdate.'
	sys.exit(3)

ntp_output = ntp_output.split()[::-1]
offset_index = ntp_output.index('offset') - 1
offset = float(ntp_output[offset_index])
offset_abs = math.fabs(offset)
offset_str = 'offset ' + '%.6f' % offset + ' sec'

if offset_abs < warning_threshold:
	print 'NTP OK: ' + offset_str
	sys.exit(0)
elif offset_abs < critical_threshold:
	print 'NTP WARNING: ' + offset_str
	sys.exit(1)
else:
	print 'NTP CRITICAL: ' + offset_str
	sys.exit(2)

print 'Error: unknwon error.'
sys.exit(3)