Code

Small syntax fix
[nagixsc.git] / nagixsc_http2nagios.py
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')
26 parser.set_defaults(cfgfile='http2nagios.cfg')
28 (options, args) = parser.parse_args()
30 cfgread = ConfigParser.SafeConfigParser()
31 cfgread.optionxform = str # We need case-sensitive options
32 cfg_list = cfgread.read(options.cfgfile)
34 if cfg_list == []:
35         print 'Config file "%s" could not be read!' % options.cfgfile
36         sys.exit(1)
38 config = {}
39 try:
40         config['ip']   = cfgread.get('server', 'ip')
41         config['port'] = cfgread.getint('server', 'port')
42         config['ssl']  = cfgread.getboolean('server', 'ssl')
43         config['cert'] = cfgread.get('server', 'sslcert')
45         config['max_xml_file_size']  = cfgread.get('server', 'max_xml_file_size')
46         config['checkresultdir'] = cfgread.get('mode_checkresult', 'dir')
48 except ConfigParser.NoOptionError, e:
49         print 'Config file error: %s ' % e
50         sys.exit(1)
52 users = {}
53 for u in cfgread.options('users'):
54         users[u] = cfgread.get('users', u)
56 ##############################################################################
58 class HTTP2NagiosHandler(MyHTTPRequestHandler):
60         def http_error(self, code, output):
61                 self.send_response(code)
62                 self.send_header('Content-Type', 'text/plain')
63                 self.end_headers()
64                 self.wfile.write(output)
65                 return
68         def do_GET(self):
69                 self.send_response(200)
70                 self.send_header('Content-Type', 'text/html')
71                 self.end_headers()
72                 self.wfile.write('''                    <html><body>
73                                 <form action="." method="post" enctype="multipart/form-data">
74                                 filename: <input type="file" name="xmlfile" /><br />
75                                 <input type="submit" />
76                                 </form>
77                         </body></html>
78                         ''')
79                 return
82         def do_POST(self):
83                 # Check Basic Auth
84                 try:
85                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
86                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
87                                 raise Exception
88                 except:
89                         self.send_response(401)
90                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
91                         self.send_header('Content-Type', 'text/plain')
92                         self.end_headers()
93                         self.wfile.write('Sorry! No action without login!')
94                         return
96                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
97                 if ctype == 'multipart/form-data':
98                         query = cgi.parse_multipart(self.rfile, pdict)
99                 xmltext = query.get('xmlfile')[0]
101                 if len(xmltext) > 0:
102                         doc = read_xml_from_string(xmltext)
103                         checks = xml_to_dict(doc)
105                         (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'], 0)
107                         if count_failed < count_services:
108                                 self.send_response(200)
109                                 self.send_header('Content-Type', 'text/plain')
110                                 self.end_headers()
111                                 self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
112                                 return
113                         else:
114                                 self.http_error(501, 'Could not write all %s check results' % count_services)
115                                 return
117                 else:
118                         self.http_error(502, 'Nag(IX)SC - No data received')
119                         return
123 def main():
124         if config['ssl'] and not os.path.isfile(config['cert']):
125                 print 'SSL certificate "%s" not found!' % config['cert']
126                 sys.exit(127)
128         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['cert'])
129         try:
130                 server.serve_forever()
131         except:
132                 server.socket.close()
134 if __name__ == '__main__':
135         print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:15667/\n\n'
136         main()