1 #!/usr/bin/python
3 #import base64
4 import datetime
5 import libxml2
6 import optparse
7 import os
8 import random
9 import string
10 import sys
12 NAGIOSCMDs = [ '/usr/local/nagios/var/rw/nagios.cmd', '/var/lib/nagios3/rw/nagios.cmd', ]
13 CHECKRESULTDIRs = [ '/usr/local/nagios/var/spool/checkresults', '/var/lib/nagios3/spool/checkresults', ]
14 MODEs = [ 'passive', 'passive_check', 'checkresult', 'checkresult_check', 'active', ]
16 parser = optparse.OptionParser()
18 parser.add_option('-u', '', dest='url', help='URL of status file (xml)')
19 parser.add_option('-f', '', dest='file', help='(Path and) file name of status file')
20 parser.add_option('-S', '', dest='schemacheck', help='Check XML against DTD')
21 parser.add_option('-s', '', dest='seconds', type='int', help='Maximum age in seconds of xml timestamp')
22 parser.add_option('-m', '', action='store_true', dest='markold', help='Mark (Set state) of too old checks as UNKNOWN')
23 parser.add_option('-O', '', dest='mode', help='Where/Howto output the results ("%s")' % '", "'.join(MODEs))
24 parser.add_option('-p', '', dest='pipe', help='Full path to nagios.cmd')
25 parser.add_option('-r', '', dest='checkresultdir', help='Full path to checkresult directory')
26 parser.add_option('-H', '', dest='host', help='Hostname to search for in XML file')
27 parser.add_option('-D', '', dest='service', help='Service description to search for in XML file')
28 parser.add_option('-v', '', action='count', dest='verb', help='Verbose output')
30 parser.set_defaults(url=None)
31 parser.set_defaults(file='nagixsc.xml')
32 parser.set_defaults(schemacheck='')
33 parser.set_defaults(seconds=14400)
34 parser.set_defaults(markold=False)
35 parser.set_defaults(mode=False)
36 parser.set_defaults(pipe=None)
37 parser.set_defaults(checkresultdir=None)
38 parser.set_defaults(host=None)
39 parser.set_defaults(service=None)
40 parser.set_defaults(verb=0)
42 (options, args) = parser.parse_args()
44 ##############################################################################
46 from nagixsc import *
48 ##############################################################################
50 if options.mode not in MODEs:
51 print 'Not an allowed mode "%s" - allowed are: %s' % (options.mode, ", ".join(MODEs))
52 sys.exit(127)
54 # Check command line options wrt mode
55 if options.mode == 'passive' or options.mode == 'passive_check':
56 debug(1, options.verb, 'Running in passive mode')
57 if options.pipe == None and options.verb <= 2:
58 for nagioscmd in NAGIOSCMDs:
59 if os.path.exists(nagioscmd):
60 options.pipe = nagioscmd
62 if options.pipe == None and options.verb <= 2:
63 print 'Need full path to the nagios.cmd pipe!'
64 sys.exit(127)
66 debug(2, options.verb, 'nagios.cmd found at %s' % options.pipe)
68 elif options.mode == 'checkresult' or options.mode == 'checkresult_check':
69 debug(1, options.verb, 'Running in checkresult mode')
70 if options.checkresultdir == None and options.verb <= 2:
71 for crd in CHECKRESULTDIRs:
72 if os.path.exists(crd):
73 options.checkresultdir = crd
75 if options.checkresultdir == None and options.verb <= 2:
76 print 'Need full path to the checkresultdir!'
77 sys.exit(127)
79 debug(2, options.verb, 'Checkresult dir: %s' % options.checkresultdir)
81 elif options.mode == 'active':
82 debug(1, options.verb, 'Running in active/plugin mode')
83 if options.host == None:
84 debug(1, options.verb, 'No host specified, using first host in XML file')
85 if options.service == None:
86 print 'No service specified on command line!'
87 sys.exit(127)
89 ##############################################################################
91 now = int(datetime.datetime.now().strftime('%s'))
93 # Get URL or file
94 if options.url != None:
95 import urllib2
97 response = urllib2.urlopen(options.url)
98 doc = libxml2.parseDoc(response.read())
99 response.close()
100 else:
101 doc = libxml2.parseFile(options.file)
104 # Check XML against DTD
105 if options.schemacheck:
106 dtd = libxml2.parseDTD(None, options.schemacheck)
107 ctxt = libxml2.newValidCtxt()
108 ret = doc.validateDtd(ctxt, dtd)
109 if ret != 1:
110 print "error doing DTD validation"
111 sys.exit(1)
112 dtd.freeDtd()
113 del dtd
114 del ctxt
117 # Check XML file basics
118 (status, statusstring) = xml_check_version(doc)
119 debug(1, options.verb, statusstring)
120 if not status:
121 print statusstring
122 sys.exit(127)
125 # Get timestamp and check it
126 filetimestamp = xml_get_timestamp(doc)
127 if not filetimestamp:
128 print 'No timestamp found in XML file, exiting because of invalid XML data...'
129 sys.exit(127)
131 timedelta = int(now) - int(filetimestamp)
132 debug(1, options.verb, 'Age of XML file: %s seconds, max allowed: %s seconds' % (timedelta, options.seconds))
135 # Put XML to Python dict
136 checks = xml_to_dict(doc, options.verb, options.host, options.service)
138 # Loop over check results and perhaps mark them as outdated
139 for check in checks:
140 check = check_mark_outdated(check, now, options.seconds, options.markold)
143 # Next steps depend on mode, output results
144 # MODE: passive
145 if options.mode == 'passive' or options.mode == 'passive_check':
146 count_services = 0
147 # Prepare
148 if options.verb <= 2:
149 pipe = open(options.pipe, "w")
150 else:
151 pipe = None
153 # Output
154 for check in checks:
155 count_services += 1
156 if check['service_description'] == None or check['service_description'] == '':
157 # Host check
158 line = '[%s] PROCESS_HOST_CHECK_RESULT;%s;%s;%s' % (now, check['host_name'], check['returncode'], check['output'].replace('\n', '\\n'))
159 else:
160 # Service check
161 line = '[%s] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s;%s' % (now, check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n'))
163 if pipe:
164 pipe.write(line + '\n')
165 debug(2, options.verb, '%s / %s: %s - "%s"' % (check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n')))
166 debug(3, options.verb, line)
168 # Close
169 if pipe:
170 pipe.close()
171 else:
172 print "Passive check results NOT written to Nagios pipe due to -vvv!"
174 # Return/Exit as a Nagios Plugin if called with mode 'passive_check'
175 if options.mode == 'passive_check':
176 returncode = 0
177 returnstring = 'OK'
178 output = ''
180 if options.markold:
181 if (now - filetimestamp) > options.seconds:
182 returnstring = 'WARNING'
183 output = '%s check results written, which are %s(>%s) seconds old' % (count_services, (now-filetimestamp), options.seconds)
184 returncode = 1
186 if not output:
187 output = '%s check results written which are %s seconds old' % (count_services, (now-filetimestamp))
189 print 'Nag(ix)SC %s - %s' % (returnstring, output)
190 sys.exit(returncode)
192 # MODE: checkresult
193 elif options.mode == 'checkresult' or options.mode == 'checkresult_check':
194 count_services = 0
195 count_failed = 0
197 chars = string.letters + string.digits
199 for check in checks:
200 count_services += 1
201 if check.has_key('timestamp'):
202 timestamp = check['timestamp']
203 else:
204 timestamp = xml_get_timestamp(xmldoc)
206 filename = os.path.join(options.checkresultdir, 'c' + ''.join([random.choice(chars) for i in range(6)]))
207 try:
208 crfile = open(filename, "w")
209 if check['service_description'] == None or check['service_description'] == '':
210 # Host check
211 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, datetime.datetime.now().ctime(), check['host_name'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
212 else:
213 # Service check
214 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\nservice_description=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, datetime.datetime.now().ctime(), check['host_name'], check['service_description'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
215 crfile.close()
217 # Create OK file
218 open(filename + '.ok', 'w').close()
219 except:
220 count_failed += 1
221 if options.mode == 'checkresult':
222 print 'Could not write checkresult files "%s(.ok)" for "%s"/"%s"!' % (filename, check['host_name'], check['service_description'])
224 if options.mode == 'checkresult_check':
225 returnstring = ''
226 output = ''
227 if count_failed == 0:
228 returnstring = 'OK'
229 returncode = 0
230 output = 'Wrote checkresult files for %s services' % count_services
231 elif count_failed == count_services:
232 returnstring = 'CRITICAL'
233 returncode = 2
234 output = 'No checkresult files could be writen!'
235 else:
236 returnstring = 'WARNING'
237 returncode = 1
238 output = 'Could not write %s out of %s checkresult files!' % (count_failed, count_services)
240 print 'Nag(ix)SC %s - %s' % (returnstring, output)
241 sys.exit(returncode)
243 if count_failed == 0:
244 sys.exit(0)
245 else:
246 sys.exit(1)
248 # MODE: active
249 elif options.mode == 'active':
251 if len(checks) > 1:
252 print 'Nag(ix)SC UNKNOWN - Found more (%s) than one host/service!' % len(checks)
253 sys.exit(3)
254 elif len(checks) == 0:
255 print 'Nag(ix)SC UNKNOWN - No check for "%s"/"%s" found in XML' % (options.host, options.service)
256 sys.exit(3)
258 print checks[0]['output']
259 sys.exit(int(checks[0]['returncode']))
261 else:
262 print 'Unknown mode! This should NEVER happen!'
263 sys.exit(127)