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')
25 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
27 parser.set_defaults(cfgfile='conf2http.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['conf_dir'] = cfgread.get('server', 'conf_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 Conf2HTTPHandler(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 path = self.path.split('/')
71 # Check Basic Auth
72 try:
73 authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
74 if not users[authdata[0]] == md5(authdata[1]).hexdigest():
75 raise Exception
76 except:
77 self.send_response(401)
78 self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
79 self.send_header('Content-Type', 'text/plain')
80 self.end_headers()
81 self.wfile.write('Sorry! No action without login!')
82 return
85 if len(path) >= 4:
86 service = path[3]
87 else:
88 service = None
90 if len(path) >= 3:
91 host = path[2]
92 else:
93 host = None
95 if len(path) >= 2:
96 configfile = path[1] + '.conf'
97 else:
98 self.http_error(500, 'No config file specified')
99 return
101 if re.search('\.\.', configfile):
102 self.http_error(500, 'Found ".." in config file name')
103 return
104 if not re.search('^[a-zA-Z0-9-_\.]+$', configfile):
105 self.http_error(500, 'Config file name contains invalid characters')
106 return
108 check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
109 if not check_config:
110 self.http_error(500, 'Could not read config file "%s"' % configfile)
111 return
113 checks = conf2dict(check_config, host, service)
114 if not checks:
115 self.http_error(500, 'No checks executed')
116 return
118 self.send_response(200)
119 self.send_header('Content-Type', 'text/xml')
120 self.end_headers()
121 self.wfile.write(xml_from_dict(checks))
123 return
127 def main():
128 if options.nossl:
129 config['ssl'] = False
131 if config['ssl'] and not os.path.isfile(config['cert']):
132 print 'SSL certificate "%s" not found!' % config['cert']
133 sys.exit(127)
135 server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['cert'])
136 try:
137 server.serve_forever()
138 except:
139 server.socket.close()
141 if __name__ == '__main__':
142 main()