Parsers Package¶
Parsers Package¶
- exception pynag.Parsers.ConfigFileNotFound(message, item=None)¶
Bases: pynag.Parsers.ParserError
This exception is thrown if we cannot locate any nagios.cfg-style config file.
- class pynag.Parsers.ExtraOptsParser(section_name=None, config_file=None)¶
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
- get(option_name, default=<object object at 0x7f1dc303a3f0>)¶
Return the value of one specific option
- get_default_config_file()¶
Return path to first readable extra-opt config-file found
According to the nagiosplugins extra-opts spec the search method is as follows
- Search for nagios.ini or nagios-plugins.ini in : splitted variable NAGIOS_CONFIG_PATH
- Search in a predefined list of files
- Return None if no config file is found
The method works as follows:
- To quote the spec on NAGIOS_CONFIG_PATH:
- “To use a custom location, set a NAGIOS_CONFIG_PATH environment variable to the set of directories that should be checked (this is a colon-separated list just like PATH). The first plugins.ini or nagios-plugins.ini file found in these directories will be used.”
- get_default_section_name()¶
According to extra-opts standard, the default should be filename of check script being run
- get_values()¶
Returns a dict with all extra-options with the granted section_name and config_file
- Results are in the form of:
- {
- ‘key’: [“possible”,”values”]
}
- getlist(option_name, default=<object object at 0x7f1dc303a3f0>)¶
Return a list of all values for option_name
- parse_file(filename)¶
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.
- Example the following the file:
- [main] name = this is a name key = value key = value2
- Would return:
- [
- {‘main’:
- {
- ‘name’: [‘this is a name’], ‘key’: [value, value2]
}
}, ]
- parse_string(string)¶
Parsers a string that is supposed to be ini-style format. See parse_file() for more ifno
- standard_locations = ['/etc/nagios/plugins.ini', '/usr/local/nagios/etc/plugins.ini', '/usr/local/etc/nagios/plugins.ini', '/etc/opt/nagios/plugins.ini', '/etc/nagios-plugins.ini', '/usr/local/etc/nagios-plugins.ini', '/etc/opt/nagios-plugins.ini']¶
- exception pynag.Parsers.LivestatusNotConfiguredException(message, item=None)¶
Bases: pynag.Parsers.ParserError
This exception is raised if we tried to autodiscover path to livestatus and failed
- class pynag.Parsers.LogFiles(maincfg=None)¶
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 mk_livestatus log output
- get_flap_alerts(**kwargs)¶
Same as self.get_log_entries, except return timeperiod transitions. Takes same parameters.
- get_log_entries(start_time=None, end_time=None, strict=True, search=None, **kwargs)¶
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:
- List of dicts
- get_logfiles() → list_of_strings¶
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
- get_notifications(**kwargs)¶
Same as self.get_log_entries, except return only notifications. Takes same parameters.
- get_state_history(start_time=None, end_time=None, host_name=None, service_description=None)¶
Returns a list of dicts, with the state history of hosts and services. Parameters behaves similar to get_log_entries
- exception pynag.Parsers.ParserError(message, item=None)¶
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.
- filename = None¶
- line_start = None¶
- message = None¶
- class pynag.Parsers.SshConfig(host, username, password=None, cfg_file=None)¶
Bases: pynag.Parsers.config
Parse object configuration files from remote host via ssh
- access(*args, **kwargs)¶
Wrapper around os.access
- exists(path)¶
Wrapper around os.path.exists
- isdir(path)¶
Behaves like os.path.isdir
- isfile(path)¶
Behaves like os.path.isfile
- islink(path)¶
Behaves like os.path.islink
- open(filename, *args, **kwargs)¶
- readlink(selfself, path)¶
Behaves like os.readlink
- stat(*args, **kwargs)¶
Wrapper around os.stat
- class pynag.Parsers.config(cfg_file=None, strict=False)¶
Parse and write nagios config files
- abspath(path)¶
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’
- access(*args, **kwargs)¶
Wrapper around os.access
- cleanup()¶
Remove configuration files that have no configuration items
- commit()¶
Write any changes that have been made to it’s appropriate file
- compareObjects(item1, item2)¶
Compares two items. Returns true if they are equal
- delete_host(object_name, user_key=None)¶
Delete a host from its configuration files
- delete_hostgroup(object_name, user_key=None)¶
Delete a hostgroup from its configuration files
- delete_object(object_type, object_name, user_key=None)¶
Delete object from configuration files
- delete_service(service_description, host_name)¶
Delete service from configuration files
- edit_object(item, field_name, new_value)¶
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_service(target_host, service_description, field_name, new_value)¶
Edit a service’s attributes
- exists(*args, **kwargs)¶
Wrapper around os.path.exists
- extended_parse()¶
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_all_commit()¶
Flag every item in the configuration to be committed This should probably only be used for debugging purposes
- get_cfg_dirs()¶
Return a list of all cfg directories used in this configuration
Example: print(get_cfg_dirs()) [‘/etc/nagios/hosts’,’/etc/nagios/objects’,...]
- get_cfg_files()¶
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’,...]
- get_cfg_value(key)¶
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” )- Returns:
- String of the first value found for
- Example:
>>> c = config() >>> log_file = c.get_cfg_value('log_file')
# Should return something like “/var/log/nagios/nagios.log”
- get_command(object_name, user_key=None)¶
Return a Command object
- get_contact(object_name, user_key=None)¶
Return a Contact object
- get_contactgroup(object_name, user_key=None)¶
Return a Contactgroup object
- get_host(object_name, user_key=None)¶
Return a host object
- get_hostdependency(object_name, user_key=None)¶
Return a hostdependency object
- get_hostgroup(object_name, user_key=None)¶
Return a hostgroup object
- get_new_item(object_type, filename)¶
Returns an empty item with all necessary metadata
- get_object(object_type, object_name, user_key=None)¶
Return a complete object dictionary
Returns None if object is not found
- get_object_types()¶
Returns a list of all discovered object types
- get_resource(resource_name)¶
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:
- String value of the resource value.
- Raises:
- KeyError if resource is not found
- ParserError if resource is not found and you do not have permissions
- get_resources()¶
Returns a list of every private resources from nagios.cfg
- get_service(target_host, service_description)¶
Return a service object
- get_servicedependency(object_name, user_key=None)¶
Return a servicedependency object
- get_servicegroup(object_name, user_key=None)¶
Return a Servicegroup object
- get_timeperiod(object_name, user_key=None)¶
Return a Timeperiod object
- get_timestamps()¶
Returns hash map of all nagios related files and their timestamps
- guess_cfg_file()¶
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
- guess_nagios_binary()¶
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
- guess_nagios_directory()¶
Returns a path to the nagios configuration directory on your system
Use this function for determining the nagios config directory in your code
- isdir(*args, **kwargs)¶
Wrapper around os.path.isdir
- isfile(*args, **kwargs)¶
Wrapper around os.path.isfile
- islink(*args, **kwargs)¶
Wrapper around os.path.islink
- item_add(item, filename)¶
Adds a new object to a specified config file
- Arguments:
- item – Item to be created filename – Filename that we are supposed to write to
- Returns:
- True on success
- Raises:
- IOError on failed save
- item_edit_field(item, field_name, new_value)¶
Modifies one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
- Example usage:
- edit_object( item, field_name=”host_name”, new_value=”examplehost.example.com”)
- Returns:
- True on success
- Raises:
- ValueError if object is not found IOError if save fails
- item_remove(item)¶
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 }
- ” )
- Returns:
- True on success
- Raises:
- ValueError if object is not found IOError if save fails
- item_remove_field(item, field_name)¶
Removes one field of a (currently existing) object. Changes are immediate (i.e. there is no commit)
- Example usage:
- item_remove_field( item, field_name=”contactgroups” )
- Returns:
- True on success
- Raises:
- ValueError if object is not found IOError if save fails
- item_rename_field(item, old_field_name, new_field_name)¶
Renames a field of a (currently existing) item. Changes are immediate (i.e. there is no commit).
- Example usage:
- item_rename_field(item, old_field_name=”normal_check_interval”, new_field_name=”check_interval”)
- Returns:
- True on success
- Raises:
- ValueError if object is not found IOError if save fails
- item_rewrite(item, str_new_item)¶
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 on success
- Raises:
- ValueError if object is not found IOError if save fails
- needs_reload()¶
Returns True if Nagios service needs reload of cfg files
Returns False if reload not needed or Nagios is not running
- needs_reparse()¶
Returns True if any Nagios configuration file has changed since last parse()
- open(filename, *args, **kwargs)¶
Wrapper around global open()
- parse(*args, **kw)¶
- parse_file(filename)¶
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.
- parse_maincfg(*args, **kw)¶
- parse_string(string, filename='None')¶
Parses a string, and returns all object definitions in that string
- Arguments:
- string – A string containing one or more object definitions filename (optional) – If filename is provided, it will be referenced when raising exceptions
- Examples:
>>> 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
- Returns:
- A list of dictionaries, that look like self.data
- print_conf(item)¶
Return a string that can be used in a configuration file
- readlink(selfself, *args, **kwargs)¶
Wrapper around os.readlink
- remove(*args, **kwargs)¶
Wrapper around os.remove
- reset()¶
- stat(*args, **kwargs)¶
Wrapper around os.stat
- write(*args, **kw)¶
- class pynag.Parsers.mk_livestatus(livestatus_socket_path=None, nagios_cfg_file=None, authuser=None)¶
Wrapper around MK-Livestatus
Example usage: s = mk_livestatus() for hostgroup s.get_hostgroups():
print(hostgroup[‘name’], hostgroup[‘num_hosts’])- get(table, *args, **kwargs)¶
Same as self.query(‘GET %s’ % (table,))
- get_contact(contact_name)¶
- get_contactgroup(name)¶
- get_contactgroups(*args, **kwargs)¶
- get_contacts(*args, **kwargs)¶
- get_host(host_name)¶
- get_hostgroup(name)¶
- get_hostgroups(*args, **kwargs)¶
- get_hosts(*args, **kwargs)¶
- get_service(host_name, service_description)¶
- get_servicegroup(name)¶
- get_servicegroups(*args, **kwargs)¶
- get_services(*args, **kwargs)¶
- query(query, *args, **kwargs)¶
- test()¶
Raises ParserError if there are problems communicating with livestatus socket
- class pynag.Parsers.object_cache(cfg_file=None, strict=False)¶
Bases: pynag.Parsers.config
Loads the configuration as it appears in objects.cache file
- get_cfg_files()¶
- class pynag.Parsers.retention(filename=None, cfg_file=None)¶
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’]
- parse()¶
Parses your status.dat file and stores in a dictionary under self.data
- Returns:
- None
- Raises:
- ParserError – if problem arises while reading status.dat ParserError – if status.dat is not found IOError – if status.dat cannot be read
- class pynag.Parsers.status(filename=None, cfg_file=None)¶
Bases: pynag.Parsers.retention
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)
- get_contactstatus(contact_name)¶
Returns a dictionary derived from status.dat for one particular contact
- Returns:
- dict
- Raises:
- ValueError if object is not found
>>> 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
- get_hoststatus(host_name)¶
Returns a dictionary derived from status.dat for one particular contact
- Returns:
- dict
- Raises:
- ValueError if object is not found
- get_servicestatus(host_name, service_description)¶
Returns a dictionary derived from status.dat for one particular service Returns:
dict- Raises:
- ValueError if object is not found