import sys
import pprint
from nagios.config import NagiosConfig, NagiosConfigError
+from fbrehm.common.getopt import BaseOptParser
#print "Modul-Suchpfade:"
#for p in sys.path:
# print " -", name
#print ""
+opt_parser = BaseOptParser(
+ version = '0.0.2',
+ prog = 'check_nagios_config.py',
+ description = u'Überprüft die Syntax einer Nagios-Konfiguration.',
+ usage = u'%s [Optionen] [<Main Nagios Konfig Datei>]'
+)
+
+opt_parser.setBaseOptionHelp( 'test', u'Simuliert nur verändernde Aktionen, wenn gesetzt' )
+opt_parser.setBaseOptionHelp( 'verbose', u'Setzt das Ausführlichkeitsniveau der Debug-Meldungen.' )
+opt_parser.setBaseOptionHelp( 'version', u'Gibt die Versionsnummer des Programms aus und beendet sich' )
+opt_parser.setBaseOptionHelp( 'help', u'Stellt diese Hilfe dar und beendet sich' )
+opt_parser.getOpts()
+
+verbose = opt_parser.options.verbose
+
+file = None
+if len(opt_parser.args):
+ file = opt_parser.args[0]
+
try:
- nagios_conf = NagiosConfig()
+ nagios_conf = NagiosConfig( verbose = verbose, new_file = file )
nagios_conf.read()
except NagiosConfigError as e:
print >> sys.stderr, e
'''
#---------------------------------------------------------------------
- def __init__( self, prog='%prog', version=None, description='' ):
+ def __init__( self, prog = '%prog',
+ version = None,
+ description = '',
+ usage = 'Usage: %s [options]'
+ ):
'''
Costructor.
@param prog: The name of the calling process (e.g. sys.argv[0])
@type version: str
@param description: The Description the process should use
@type description: str
+ @param usage: An usage string fro the help screen, must have a '%s' for the program name
+ @type usage: str
@return: None
'''
self.prog = prog
self.version = version
self.description = description
- self.usage = 'Usage: %s [options]' %(prog)
+ self.usage = usage %(prog)
self.options = None
self.args = None
self.parsed = False
self.parser = OptionParser(
- prog=self.prog,
- version=self.version,
- description=self.description
+ prog = self.prog,
+ version = self.version,
+ description = self.description,
+ usage = self.usage
)
self.addOption(
help = 'set the verbosity level'
)
+ #----------------------------------------------------------------------
def getOpts(self):
'''
The baseimplentation of getOpts. It ensures that evry class
self.options, self.args = self.parser.parse_args()
self.parsed = True
+ #----------------------------------------------------------------------
def addOption(self, *targs, **kwargs):
'''
This Method adds the options to the parser instance.
if not self.__options_set:
self.__options_set = True
+ #----------------------------------------------------------------------
+ def setBaseOptionHelp( self, option_name, option_help ):
+ '''This method sets the help text of the named option.
+ @param option_name: The name of the option to change
+ @type option_name: str
+ @param option_help: The new option help text
+ @type option_help: str
+ @return: None
+ @rtype: None
+ '''
+
+ if not len(option_name):
+ raise SyntaxError( "empty option name given." )
+
+ as_long_option = True
+ if len(option_name) == 1: as_long_option = False
+
+ for option in self.parser.option_list:
+ opt_found = False
+ if as_long_option:
+ o = '--' + option_name
+ for opt in option._long_opts:
+ if o == opt:
+ opt_found = True
+ break
+ else:
+ o = '-' + option_name
+ for opt in option._short_opts:
+ if o == opt:
+ opt_found = True
+ break
+ if opt_found:
+ option.help = option_help
+ break
#---------------------------------------------------------------------
return repr(dump)
#------------------------------------------------------
- def __init__( self, new_file = file_name, ignore_empty_object_props = True ):
- "Konstruktor."
+ def __init__( self, new_file = None,
+ ignore_empty_object_props = True,
+ verbose = 0, ):
+ """Constructor.
+ @param new_file: The main nagios configuration file
+ @type new_file: str
+ @param ignore_empty_object_props: should empty object prperties ignored? default: True
+ @type ignore_empty_object_props: bool
+ @param verbose: verbosity level (default: 0)
+ @type verbose: int
+ @return: None
+ @rtype: None
+
+ """
+
+ self.verbose = verbose
+ loglevel = logging.WARNING
+ logformat = '%(levelname)s: %(message)s'
+ if verbose == 1:
+ loglevel = logging.INFO
+ elif verbose > 1:
+ loglevel = logging.DEBUG
+ logformat = '%(name)s - %(module)s.%(funcName)s(%(lineno)d) - %(levelname)s: %(message)s'
# Logging-Setup
self.logger = logging.getLogger('nagiosConfig')
- self.logger.setLevel(logging.DEBUG)
+ self.logger.setLevel(loglevel)
ch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)
+ ch.setLevel(loglevel)
- formatter = logging.Formatter("%(name)s - %(funcName)s(%(lineno)d) - %(levelname)s - %(message)s")
+ formatter = logging.Formatter(logformat)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
+ # Other properties
+
+ # Konfigurationsverzeichnis von Nagios
+ self.default_conf_dir = os.sep + os.path.join('etc', 'nagios')
+
+ # Basename der Nagios-Konfigurationsdatei
+ self.default_file_base = 'nagios.cfg'
+
+ # Kompletter Pfad der Nagios-Konfigurationsdatei
+ self.default_file_name = os.path.join( self.default_conf_dir, self.default_file_base )
+
+ if new_file is None:
+ new_file = self.default_file_name
self.file_name = self.canonize_file(new_file)
self.conf = {}
self.objects = {}
self.file_name = my_file
return my_file
- raise NagiosConfigError( "Nagios-Konfigurationsdatei nicht gefunden." )
+ raise NagiosConfigError( "Nagios config file not found." )
return None
#------------------------------------------------------
def read( self ):
"Liest die in self.file_name hinterlegte Konfigurationsdatei ein und legt das Gelesene in self.conf ab"
+ self.logger.info( "Reading configuration file {0!r} ...".format( self.file_name ) )
+
try:
file = open( self.file_name, 'rU' )
except IOError as e:
self.read_objectfile(file_name)
pp = pprint.PrettyPrinter( indent = 4, depth = 6, width = 120 )
- self.logger.debug( "Gelesene Objekte:\n{0}".format( pp.pformat( self.objects_read ) ) )
+ self.logger.debug( "Read objects:\n{0}".format( pp.pformat( self.objects_read ) ) )
del self.struct_verifier
"Checkt absolute Angabe und Vorhandensein der übergebenen Datei bzw. Verzeichnis"
directive = 'cfg_file'
- file_type = 'Datei'
+ file_type = 'file'
if as_dir:
directive = 'cfg_dir'
- file_type = 'Verzeichnis'
+ file_type = 'directory'
if not os.path.isabs(file):
- self.logger.error( "Keine absolute Pfadangabe in {0}={1}".format( directive, file ) )
+ self.logger.error( "No absolute path given in {0}={1}".format( directive, file ) )
return None
if not os.path.exists(file):
- self.logger.error( "{0} {1} existiert nicht.".format( file_type, file ) )
+ self.logger.error( "{0} {1} doesn't exists.".format( file_type, file ) )
return None
if as_dir:
if not os.path.isdir(file):
- self.logger.error( "Verzeichnis {0} ist keine normales Verzeichnis.".format(file) )
+ self.logger.error( "Directory {0} isn't a regular directory.".format(file) )
return None
else:
if not os.path.isfile(file):
- self.logger.error( "Datei {0} ist keine normale Datei.".format(file) )
+ self.logger.error( "File {0} isn't a regular file.".format(file) )
return None
return os.path.realpath(file)