Parse and write nagios config files
Return the absolute path of a given relative path.
The current working directory is assumed to be the dirname of nagios.cfg
Example: >>> c = config(cfg_file=”/etc/nagios/nagios.cfg”) >>> c.abspath(‘nagios.cfg’) ‘/etc/nagios/nagios.cfg’ >>> c.abspath(‘/etc/nagios/nagios.cfg’) ‘/etc/nagios/nagios.cfg’
Wrapper around os.access
Remove configuration files that have no configuration items
Write any changes that have been made to it’s appropriate file
Compares two items. Returns true if they are equal
Delete a host from its configuration files
Delete a hostgroup from its configuration files
Delete object from configuration files
Delete service from configuration files
Modifies a (currently existing) item. Changes are immediate (i.e. there is no commit)
Example Usage: edit_object( item, field_name=”host_name”, new_value=”examplehost.example.com”)
THIS FUNCTION IS DEPRECATED. USE item_edit_field() instead
Edit a service’s attributes
Wrapper around os.path.exists
This parse is used after the initial parse() command is run. It is only needed if you want extended meta information about hosts or other objects
Flag every item in the configuration to be committed This should probably only be used for debugging purposes
Return a list of all cfg directories used in this configuration
Example: print(get_cfg_dirs()) [‘/etc/nagios/hosts’,’/etc/nagios/objects’,...]
Return a list of all cfg files used in this configuration
Filenames are normalised so that if nagios.cfg specifies relative filenames we will convert it to fully qualified filename before returning.
Example: print(get_cfg_files()) [‘/etc/nagios/hosts/host1.cfg’,’/etc/nagios/hosts/host2.cfg’,...]
Returns one specific value from your nagios.cfg file, None if value is not found. Arguments:
key - what attribute to fetch from nagios.cfg (example: “command_file” )
>>> c = config()
>>> log_file = c.get_cfg_value('log_file')
# Should return something like “/var/log/nagios/nagios.log”
Return a Command object
Return a Contact object
Return a Contactgroup object
Return a host object
Return a hostdependency object
Return a hostgroup object
Returns an empty item with all necessary metadata
Return a complete object dictionary
Returns None if object is not found
Returns a list of all discovered object types
Get a single resource value which can be located in any resource.cfg file
- Arguments:
- resource_name: Name as it appears in resource file (i.e. $USER1$)
Returns a list of every private resources from nagios.cfg
Return a service object
Return a servicedependency object
Return a Servicegroup object
Return a Timeperiod object
Returns hash map of all nagios related files and their timestamps
Returns a path to any nagios.cfg found on your system
Use this function if you don’t want specify path to nagios.cfg in your code and you are confident that it is located in a common location
Returns a path to any nagios binary found on your system
Use this function if you don’t want specify path to the nagios binary in your code and you are confident that it is located in a common location
Returns a path to the nagios configuration directory on your system
Use this function for determining the nagios config directory in your code
Wrapper around os.path.isdir
Wrapper around os.path.isfile
Wrapper around os.path.islink
Adds a new object to a specified config file
Modifies one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
Delete one specific item from its configuration files
- Arguments:
- item – Item that is to be rewritten str_new_item – str representation of the new item
- Examples:
- item_rewrite( item, “define service {
name example-service register 0 }
Removes one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
Renames a field of a (currently existing) item. Changes are immediate (i.e. there is no commit).
Completely rewrites item with string provided.
- Arguments:
- item – Item that is to be rewritten str_new_item – str representation of the new item
- Examples:
- item_rewrite( item, “define service {
name example-service register 0 }
Returns True if Nagios service needs reload of cfg files
Returns False if reload not needed or Nagios is not running
Returns True if any Nagios configuration file has changed since last parse()
Wrapper around global open()
Parses a nagios object configuration file and returns lists of dictionaries.
This is more or less a wrapper around config.parse_string, so reading documentation there is useful.
Parses a string, and returns all object definitions in that string
>>> test_string = "define host {\nhost_name examplehost\n}\n"
>>> test_string += "define service {\nhost_name examplehost\nservice_description example service\n}\n"
>>> c = config()
>>> result = c.parse_string(test_string)
>>> for i in result: print i.get('host_name'), i.get('service_description', None)
examplehost None
examplehost example service
Return a string that can be used in a configuration file
Wrapper around os.readlink
Wrapper around os.remove
Wrapper around os.stat
Bases: pynag.Parsers.ParserError
This exception is thrown if we cannot locate any nagios.cfg-style config file.
Bases: object
Get Nagios Extra-Opts from a config file as specified by http://nagiosplugins.org/extra-opts
We could ALMOST use pythons ConfParser but nagios plugin team thought it would be a good idea to support multiple values per key, so a dict datatype no longer works.
Its a shame because we have to make our own “ini” parser as a result
Usage:
# cat /etc/nagios/plugins.ini [main] host_name = localhost [other section] host_name = example.com # EOF
e = ExtraOptsParser(section_name=’main’, config_file=’/etc/nagios/plugins.ini’) e.get(‘host_name’) # returns “localhost” e.get_values() # Returns a dict of all the extra opts e.getlist(‘host_name’) # returns all values of host_name (if more than one were specified) in a list
Return the value of one specific option
Return path to first readable extra-opt config-file found
According to the nagiosplugins extra-opts spec the search method is as follows
The method works as follows:
According to extra-opts standard, the default should be filename of check script being run
Returns a dict with all extra-options with the granted section_name and config_file
}
Return a list of all values for option_name
Parses an ini-file and returns a dict of the ini values.
The datatype returned is a list of sections where each section is a dict of values.
}
}, ]
Parsers a string that is supposed to be ini-style format. See parse_file() for more ifno
Wrapper around MK-Livestatus
Example usage: s = Livestatus() for hostgroup s.get_hostgroups():
print(hostgroup[‘name’], hostgroup[‘num_hosts’])
Same as self.query(‘GET %s’ % (table,))
Raises ParserError if there are problems communicating with livestatus socket
Bases: pynag.Parsers.ParserError
This exception is raised if we tried to autodiscover path to livestatus and failed
Bases: object
Parses Logfiles defined in nagios.cfg and allows easy access to its content in python-friendly arrays of dicts. Output should be more or less compatible with Livestatus log output
Same as self.get_log_entries, except return timeperiod transitions. Takes same parameters.
Get Parsed log entries for given timeperiod. Arguments:
start_time – unix timestamp. if None, return all entries from today end_time – If specified, only fetch log entries older than this (unix timestamp) strict – If True, only return entries between start_time and end_time, if False,
– then return entries that belong to same log files as given timesetsearch – If provided, only return log entries that contain this string (case insensitive) kwargs – All extra arguments are provided as filter on the log entries. f.e. host_name=”localhost”
Returns a list with full path to every logfile used by nagios, sorted by modification time
Newest logfile is at the front of the list so usually nagios.log comes first, followed by archivelogs
Same as self.get_log_entries, except return only notifications. Takes same parameters.
Returns a list of dicts, with the state history of hosts and services. Parameters behaves similar to get_log_entries
Bases: pynag.Parsers.Livestatus
Wrapps around multiple Livesatus instances and aggregates the results of queries.
>>> m = MultiSite()
>>> m.add_backend(path='/var/spool/nagios/livestatus.socket', name='local')
>>> m.add_backend(path='127.0.0.1:5992', name='remote')
Add a new livestatus backend to this instance.
Returns a list of mk_livestatus instances
Behaves like mk_livestatus.query() except results are aggregated from multiple backends
Bases: pynag.Parsers.Config
Loads the configuration as it appears in objects.cache file
Bases: exceptions.Exception
ParserError is used for errors that the Parser has when parsing config.
Typical usecase when there is a critical error while trying to read configuration.
Easy way to parse the content of retention.dat
After calling parse() contents of retention.dat are kept in self.data
Example Usage: >>> #r = retention() >>> #r.parse() >>> #print r >>> #print r.data[‘info’]
Parses your status.dat file and stores in a dictionary under self.data
Bases: pynag.Parsers.Config
Parse object configuration files from remote host via ssh
Wrapper around os.access
Wrapper around os.path.exists
Behaves like os.path.isdir
Behaves like os.path.isfile
Behaves like os.path.islink
Behaves like os.readlink
Wrapper around os.stat
Bases: pynag.Parsers.RetentionDat
Easy way to parse status.dat file from nagios
After calling parse() contents of status.dat are kept in status.data Example usage: >>> s = status() >>> s.parse() >>> keys = s.data.keys() >>> ‘info’ in keys True >>> ‘programstatus’ in keys True >>> for service in s.data.get(‘servicestatus’,[]): ... host_name=service.get(‘host_name’, None) ... description=service.get(‘service_description’,None)
Returns a dictionary derived from status.dat for one particular contact
>>> s = status()
>>> s.get_contactstatus(contact_name='invalid_contact')
ValueError('invalid_contact',)
>>> first_contact = s.data['contactstatus'][0]['contact_name']
>>> s.get_contactstatus(first_contact)['contact_name'] == first_contact
True
Returns a dictionary derived from status.dat for one particular contact
Returns a dictionary derived from status.dat for one particular service Returns:
dict
Bases: pynag.Parsers.Config
This class is here only for backwards compatibility. Use Config instead.
Bases: pynag.Parsers.Livestatus
This class is here only for backwards compatibility. Use Livestatus instead.
Bases: pynag.Parsers.ObjectCache
This class is here only for backwards compatibility. Use ObjectCache instead.
Bases: pynag.Parsers.RetentionDat
This class is here only for backwards compatibility. Use RetentionDat instead.
Bases: pynag.Parsers.StatusDat
This class is here only for backwards compatibility. Use StatusDat instead.