1 #!/usr/bin/python
3 import ConfigParser
4 import base64
5 import cgi
6 import optparse
7 import os
8 import re
9 import sys
11 try:
12 from hashlib import md5
13 except ImportError:
14 from md5 import md5
16 ##############################################################################
18 from nagixsc import *
20 ##############################################################################
22 parser = optparse.OptionParser()
24 parser.add_option('-c', '', dest='cfgfile', help='Config file')
25 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
27 parser.set_defaults(cfgfile='http2nagios.cfg')
29 (options, args) = parser.parse_args()
31 cfgread = ConfigParser.SafeConfigParser()
32 cfgread.optionxform = str # We need case-sensitive options
33 cfg_list = cfgread.read(options.cfgfile)
35 if cfg_list == []:
36 print 'Config file "%s" could not be read!' % options.cfgfile
37 sys.exit(1)
39 config = {}
40 try:
41 config['ip'] = cfgread.get('server', 'ip')
42 config['port'] = cfgread.getint('server', 'port')
43 config['ssl'] = cfgread.getboolean('server', 'ssl')
44 config['cert'] = cfgread.get('server', 'sslcert')
46 config['max_xml_file_size'] = cfgread.get('server', 'max_xml_file_size')
47 config['checkresultdir'] = cfgread.get('mode_checkresult', 'dir')
49 except ConfigParser.NoOptionError, e:
50 print 'Config file error: %s ' % e
51 sys.exit(1)
53 users = {}
54 for u in cfgread.options('users'):
55 users[u] = cfgread.get('users', u)
57 ##############################################################################
59 class HTTP2NagiosHandler(MyHTTPRequestHandler):
61 def http_error(self, code, output):
62 self.send_response(code)
63 self.send_header('Content-Type', 'text/plain')
64 self.end_headers()
65 self.wfile.write(output)
66 return
69 def do_GET(self):
70 self.send_response(200)
71 self.send_header('Content-Type', 'text/html')
72 self.end_headers()
73 self.wfile.write(''' <html><body>
74 <form action="." method="post" enctype="multipart/form-data">
75 filename: <input type="file" name="xmlfile" /><br />
76 <input type="submit" />
77 </form>
78 </body></html>
79 ''')
80 return
83 def do_POST(self):
84 # Check Basic Auth
85 try:
86 authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
87 if not users[authdata[0]] == md5(authdata[1]).hexdigest():
88 raise Exception
89 except:
90 self.send_response(401)
91 self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
92 self.send_header('Content-Type', 'text/plain')
93 self.end_headers()
94 self.wfile.write('Sorry! No action without login!')
95 return
97 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
98 if ctype == 'multipart/form-data':
99 query = cgi.parse_multipart(self.rfile, pdict)
100 xmltext = query.get('xmlfile')[0]
102 if len(xmltext) > 0:
103 doc = read_xml_from_string(xmltext)
104 checks = xml_to_dict(doc)
106 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'], 0)
108 if count_failed < count_services:
109 self.send_response(200)
110 self.send_header('Content-Type', 'text/plain')
111 self.end_headers()
112 self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
113 return
114 else:
115 self.http_error(501, 'Could not write all %s check results' % count_services)
116 return
118 else:
119 self.http_error(502, 'Nag(IX)SC - No data received')
120 return
124 def main():
125 if options.nossl:
126 config['ssl'] = False
128 if config['ssl'] and not os.path.isfile(config['cert']):
129 print 'SSL certificate "%s" not found!' % config['cert']
130 sys.exit(127)
132 server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['cert'])
133 try:
134 server.serve_forever()
135 except:
136 server.socket.close()
138 if __name__ == '__main__':
139 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:15667/\n\n'
140 main()