Code

conf2http can now use SSL!
[nagixsc.git] / nagixsc_conf2http.py
1 #!/usr/bin/python
3 import ConfigParser
4 import base64
5 import optparse
6 import os
7 import re
8 import subprocess
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='conf2http.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['conf_dir']         = cfgread.get('server', 'conf_dir')
47 except ConfigParser.NoOptionError, e:
48         print 'Config file error: %s ' % e
49         sys.exit(1)
51 users = {}
52 for u in cfgread.options('users'):
53         users[u] = cfgread.get('users', u)
55 ##############################################################################
57 class Conf2HTTPHandler(MyHTTPRequestHandler):
59         def http_error(self, code, output):
60                 self.send_response(code)
61                 self.send_header('Content-Type', 'text/plain')
62                 self.end_headers()
63                 self.wfile.write(output)
64                 return
67         def do_GET(self):
68                 path = self.path.split('/')
70                 # Check Basic Auth
71                 try:
72                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
73                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
74                                 raise Exception
75                 except:
76                         self.send_response(401)
77                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
78                         self.send_header('Content-Type', 'text/plain')
79                         self.end_headers()
80                         self.wfile.write('Sorry! No action without login!')
81                         return
84                 if len(path) >= 4:
85                         service = path[3]
86                 else:
87                         service = None
89                 if len(path) >= 3:
90                         host = path[2]
91                 else:
92                         host = None
94                 if len(path) >= 2:
95                         configfile = path[1] + '.conf'
96                 else:
97                         self.http_error(500, 'No config file specified')
98                         return
100                 if re.search('\.\.', configfile):
101                         self.http_error(500, 'Found ".." in config file name')
102                         return
103                 if not re.search('^[a-zA-Z0-9-_\.]+$', configfile):
104                         self.http_error(500, 'Config file name contains invalid characters')
105                         return
107                 check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
108                 if not check_config:
109                         self.http_error(500, 'Could not read config file "%s"' % configfile)
110                         return
112                 checks = conf2dict(check_config, host, service)
113                 if not checks:
114                         self.http_error(500, 'No checks executed')
115                         return
117                 self.send_response(200)
118                 self.send_header('Content-Type', 'text/xml')
119                 self.end_headers()
120                 self.wfile.write(xml_from_dict(checks))
122                 return
126 def main():
127         if config['ssl'] and not os.path.isfile(config['cert']):
128                 print 'SSL certificate "%s" not found!' % config['cert']
129                 sys.exit(127)
131         server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['cert'])
132         try:
133                 server.serve_forever()
134         except:
135                 server.socket.close()
137 if __name__ == '__main__':
138         main()