Code

Reorder daemonizing (creation of PID file)
[nagixsc.git] / nagixsc_conf2xml.py
1 #!/usr/bin/python
3 import optparse
4 import sys
5 import urllib2
7 ##############################################################################
9 from nagixsc import *
11 ##############################################################################
13 parser = optparse.OptionParser()
15 parser.add_option('-c', '', dest='conffile', help='Config file')
16 parser.add_option('-o', '', dest='outfile', help='Output file name, "-" for STDOUT or HTTP POST URL')
17 parser.add_option('-e', '', dest='encoding', help='Encoding ("%s")' % '", "'.join(available_encodings()) )
18 parser.add_option('-H', '', dest='host', help='Hostname/section to search for in config file')
19 parser.add_option('-D', '', dest='service', help='Service description to search for in config file (needs -H)')
20 parser.add_option('-l', '', dest='httpuser', help='HTTP user name, if outfile is HTTP(S) URL')
21 parser.add_option('-a', '', dest='httppasswd', help='HTTP password, if outfile is HTTP(S) URL')
22 parser.add_option('-v', '', action='count', dest='verb', help='Verbose output')
24 parser.set_defaults(conffile='nagixsc.conf')
25 parser.set_defaults(outfile='-')
26 parser.set_defaults(encoding='base64')
27 parser.set_defaults(host=None)
28 parser.set_defaults(service=None)
29 parser.set_defaults(verb=0)
31 (options, args) = parser.parse_args()
33 ##############################################################################
35 if not check_encoding(options.encoding):
36         print 'Wrong encoding method "%s"!' % options.encoding
37         print 'Could be one of: "%s"' % '", "'.join(available_encodings())
38         sys.exit(127)
40 ##############################################################################
42 config = read_inifile(options.conffile)
44 if not config:
45         print 'Config file "%s" could not be read!' % options.conffile
46         sys.exit(5)
48 checks = conf2dict(config, options.host, options.service)
50 xmldoc = xml_from_dict(checks, options.encoding)
52 if options.outfile.startswith('http'):
53         (headers, body) = encode_multipart(xmldoc, options.httpuser, options.httppasswd)
55         try:
56                 response = urllib2.urlopen(urllib2.Request(options.outfile, body, headers)).read()
57         except urllib2.HTTPError, error:
58                 print error
59                 sys.exit(6)
60         except urllib2.URLError, error:
61                 print error.reason[1]
62                 sys.exit(7)
64         print response
66 elif options.outfile == '-':
67         xmldoc.saveFormatFile('-', format=1)
69 else:
70         xmldoc.saveFile(options.outfile)