Parsers Package

Parsers Package

This module contains low-level Parsers for nagios configuration and status objects.

Hint: If you are looking to parse some nagios configuration data, you probably want pynag.Model module instead.

The highlights of this module are:

class Config: For Parsing nagios local nagios configuration files class Livestatus: To connect to MK-Livestatus class StatusDat: To read info from status.dat (not used a lot, migrate to mk-livestatus) class LogFiles: To read nagios log-files class MultiSite: To talk with multiple Livestatus instances

class pynag.Parsers.Config(cfg_file=None, strict=False)

Bases: object

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

Args:

path: relative path to be transformed into absolute path. (string)

Returns:

Absolute path of given relative path.

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

Compares every key: value pair for both items. If anything is different, the items will not be considered equal.

Args:
item1, item2: Items to be compared.

Returns:

True – Items are equal

False – Items are not equal

delete_host(object_name, user_key=None)

Delete a host from its configuration files

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

True on success.
delete_hostgroup(object_name, user_key=None)

Delete a hostgroup from its configuration files

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

True on success.
delete_object(object_type, object_name, user_key=None)

Delete object from configuration files

Args:

object_type: Type of the object to delete from configuration files.

object_name: Name of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

True on success.
delete_service(service_description, host_name)

Delete service from configuration files

Args:

service_description: service_description field value of the object to delete from configuration files.

host_name: host_name field value of the object to delete from configuration files.

Returns:

True on success.
edit_object(item, field_name, new_value)

Modifies a (currently existing) item.

Changes are immediate (i.e. there is no commit)

Args:

item: Item to modify.

field_name: Field that will be updated.

new_value: Updated value of field field_name

Example Usage:
edit_object( item, field_name=”host_name”, new_value=”examplehost.example.com”)
Returns:
True on success

Warning

THIS FUNCTION IS DEPRECATED. USE item_edit_field() instead

edit_service(target_host, service_description, field_name, new_value)

Edit a service’s attributes

Takes a host, service_description pair to identify the service to modify and sets its field field_name to new_value.

Args:

target_host: name of the host to which the service is attached to. (string)

service_description: Service description of the service to modify. (string)

field_name: Field to modify. (string)

new_value: Value to which the field_name field will be updated (string)

Returns:

True on success

Raises:

ParserError if the service is not found
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()

Parses the main config file for configuration directories

Returns:

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.

Returns:

List of all configurations files used in the configuration.

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

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_contact(object_name, user_key=None)

Return a Contact object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_contactgroup(object_name, user_key=None)

Return a Contactgroup object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_host(object_name, user_key=None)

Return a host object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_hostdependency(object_name, user_key=None)

Return a hostdependency object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_hostgroup(object_name, user_key=None)

Return a hostgroup object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_new_item(object_type, filename)

Returns an empty item with all necessary metadata

Creates a new item dict and fills it with usual metadata:

  • object_type : object_type (arg)
  • filename : filename (arg)
  • template_fields = []
  • needs_commit = None
  • delete_me = None
  • defined_attributes = {}
  • inherited_attributes = {}
  • raw_definition = “define %s {nn} % object_type”

Args:

object_type: type of the object to be created (string)

filename: Path to which the item will be saved (string)

Returns:

A new item with default metadata
get_object(object_type, object_name, user_key=None)

Return a complete object dictionary

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: User defined key. Default None. (string)

Returns:

The item found to match all the criterias.

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

Args:

target_host: host_name field of the service to be returned. This is the host to which is attached the service.

service_description: service_description field of the service to be returned.

Returns:

The item found to match all the criterias.
get_servicedependency(object_name, user_key=None)

Return a servicedependency object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_servicegroup(object_name, user_key=None)

Return a Servicegroup object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
get_timeperiod(object_name, user_key=None)

Return a Timeperiod object

Args:

object_name: object_name field value of the object to delete from configuration files.

user_key: user_key to pass to get_object()

Returns:

The item found to match all the criterias.
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

Checked locations are as follows:

  • /etc/nagios/nagios.cfg
  • /etc/nagios3/nagios.cfg
  • /usr/local/nagios/etc/nagios.cfg
  • /nagios/etc/nagios/nagios.cfg
  • ./nagios.cfg
  • ./nagios/nagios.cfg
  • /etc/icinga/icinga.cfg
  • /usr/local/icinga/etc/icinga.cfg
  • ./icinga.cfg
  • ./icinga/icinga.cfg
  • /etc/naemon/naemon.cfg
  • /usr/local/naemon/etc/naemon.cfg
  • ./naemon.cfg
  • ./naemon/naemon.cfg
  • /etc/shinken/shinken.cfg

Returns:

str. Path to the nagios.cfg or equivalent file

None if couldn’t find a file in any of these locations.

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

Checked locations are as follows:

  • /usr/bin/nagios
  • /usr/sbin/nagios
  • /usr/local/nagios/bin/nagios
  • /nagios/bin/nagios
  • /usr/bin/icinga
  • /usr/sbin/icinga
  • /usr/bin/naemon
  • /usr/sbin/naemon
  • /usr/local/naemon/bin/naemon.cfg
  • /usr/bin/shinken
  • /usr/sbin/shinken

Returns:

str. Path to the nagios binary

None if could not find a binary in any of those locations

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

Returns:

str. directory containing the nagios.cfg file

Raises:

pynag.Parsers.ConfigFileNotFound if cannot guess config file location.
isdir(*args, **kwargs)

Wrapper around os.path.isdir

isfile(*args, **kwargs)

Wrapper around os.path.isfile

Wrapper around os.path.islink

item_add(item, filename)

Adds a new object to a specified config file.

Args:

item: Item to be created

filename: Filename that we are supposed to write the new item to. This is the path to the file. (string)

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)

Args:

item: Item to be modified. Its field field_name will be set to new_value.

field_name: Name of the field that will be modified. (str)

new_value: Value to which will be set the field field_name. (str)

Example usage::
edit_object( item, field_name=”host_name”, new_value=”examplehost.example.com”) # doctest: +SKIP
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

Args:

item: Item that is to be rewritten

str_new_item: string representation of the new item

Examples::
item_remove( item, “define service {n name example-service n register 0 n }n” )

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)

Args:

item: Item to remove field from.

field_name: Field to remove. (string)

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).

Args:

item: Item to modify.

old_field_name: Name of the field that will have its name changed. (string)

new_field_name: New name given to old_field_name (string)

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.

Args:

item: Item that is to be rewritten

str_new_item: str representation of the new item

Examples::
item_rewrite( item, “define service {n name example-service n register 0 n }n” )

Returns:

True on success

Raises:

ValueError if object is not found

IOError if save fails

listdir(*args, **kwargs)

Wrapper around os.listdir

needs_reload()

Checks if the Nagios service needs a reload.

Returns:

True if Nagios service needs reload of cfg files

False if reload not needed or Nagios is not running

needs_reparse()

Checks if the Nagios configuration needs to be reparsed.

Returns:

True if any Nagios configuration file has changed since last parse()
open(filename, *args, **kwargs)

Wrapper around global open()

Simply calls global open(filename, *args, **kwargs) and passes all arguments as they are received. See global open() function for more details.

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.

Args:

filename: Path to the file to parse (string)

Returns:

A list containing elements parsed by parse_string()
parse_maincfg(*args, **kw)
parse_string(string, filename='None')

Parses a string, and returns all object definitions in that string

Args:

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

Raises:

print_conf(item)

Return a string that can be used in a configuration file

Args:

item: Item to be dumped as a string.

Returns:

String representation of item.

Wrapper around os.readlink

remove(*args, **kwargs)

Wrapper around os.remove

reset()

Reinitializes the data of a parser instance to its default values.

stat(*args, **kwargs)

Wrapper around os.stat

write(*args, **kw)
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 0x7f1af2ca8570>)

Return the value of one specific option

Args:

option_name: The value set to this option will be returned

Returns:

The value of option_name

Raises:

ValueError when option_name cannot be found in options
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:

  1. Search for nagios.ini or nagios-plugins.ini in : splitted variable NAGIOS_CONFIG_PATH
  2. Search in a predefined list of files
  3. 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 0x7f1af2ca8570>)

Return a list of all values for option_name

Args:

option_name: All the values set to this option will be returned

Returns:

List containing all the options set to option_name

Raises:

ValueError when option_name cannot be found in options
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.

Args:

filename: Full path to the ini-file to be parsed.

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)

Parses a string that is supposed to be ini-style format.

See parse_file() for more info

Args:

string: String to be parsed. Should be in ini-file format.

Returns:

Dictionnary containing all the sections of the ini-file and their respective data.

Raises:

ParserError when line does not follow the ini format.
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']
class pynag.Parsers.Livestatus(livestatus_socket_path=None, nagios_cfg_file=None, authuser=None)

Bases: object

Wrapper around MK-Livestatus

Example usage:

s = Livestatus()
for hostgroup s.get_hostgroups():
    print(hostgroup['name'], hostgroup['num_hosts'])
get(table, *args, **kwargs)

Same as self.query(‘GET %s’ % (table,))

Extra arguments will be appended to the query.

Args:

table: Table from which the data will be retrieved

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Example:

get('contacts', 'Columns: name alias')

Returns:

Answer from livestatus in python format.
get_contact(contact_name)

Performs a GET query for a particular contact

This performs:

'''GET contacts
Filter: contact_name = %s''' % contact_name

Args:

contact_name: name of the contact to obtain livestatus data from

Returns:

Answer from livestatus in python format.
get_contactgroup(name)

Performs a GET query for a particular contactgroup

This performs:

'''GET contactgroups
Filter: contactgroup_name = %s''' % contactgroup_name

Args:

contactgroup_name: name of the contactgroup to obtain livestatus data from

Returns:

Answer from livestatus in python format.
get_contactgroups(*args, **kwargs)

Performs a GET query for all contactgroups

This performs:

'''GET contactgroups
%s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
get_contacts(*args, **kwargs)

Performs a GET query for all contacts

This performs:

'''GET contacts
%s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
get_host(host_name)

Performs a GET query for a particular host

This performs:

'''GET hosts
Filter: host_name = %s''' % host_name

Args:

host_name: name of the host to obtain livestatus data from

Returns:

Answer from livestatus in python format.
get_hostgroup(name)

Performs a GET query for a particular hostgroup

This performs:

'''GET hostgroups
Filter: hostgroup_name = %s''' % hostgroup_name

Args:

hostgroup_name: name of the hostgroup to obtain livestatus data from

Returns:

Answer from livestatus in python format.
get_hostgroups(*args, **kwargs)

Performs a GET query for all hostgroups

This performs:

'''GET hostgroups
%s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
get_hosts(*args, **kwargs)

Performs a GET query for all hosts

This performs:

'''GET hosts %s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
get_service(host_name, service_description)

Performs a GET query for a particular service

This performs:

'''GET services
Filter: host_name = %s
Filter: service_description = %s''' % (host_name, service_description)

Args:

host_name: name of the host the target service is attached to.

service_description: Description of the service to obtain livestatus data from.

Returns:

Answer from livestatus in python format.
get_servicegroup(name)

Performs a GET query for a particular servicegroup

This performs:

'''GET servicegroups
Filter: servicegroup_name = %s''' % servicegroup_name

Args:

servicegroup_name: name of the servicegroup to obtain livestatus data from

Returns:

Answer from livestatus in python format.
get_servicegroups(*args, **kwargs)

Performs a GET query for all servicegroups

This performs:

'''GET servicegroups
%s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
get_services(*args, **kwargs)

Performs a GET query for all services

This performs:

'''GET services
%s %s''' % (*args, **kwargs)

Args:

args, kwargs: These will be appendend to the end of the query to perform additionnal instructions.

Returns:

Answer from livestatus in python format.
query(query, *args, **kwargs)

Performs LQL queries the livestatus socket

Queries are corrected and convienient default data are added to the query before sending it to the socket.

Args:

query: Query to be passed to the livestatus socket (string)

args, kwargs: Additionnal parameters that will be sent to pynag.Utils.grep_to_livestatus(). The result will be appended to the query.

Returns:

Answer from livestatus. It will be in python format unless specified otherwise.

Raises:

ParserError if problems connecting to livestatus.
test(raise_error=True)

Test if connection to livestatus socket is working

Args:

raise_error: If set to True, raise exception if test fails,otherwise return False

Raises:

ParserError if raise_error == True and connection fails

Returns:

True – Connection is OK False – there are problems and raise_error==False
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

Content is stored in python-friendly arrays of dicts. Output should be more or less compatible with mk_livestatus log output

get_flap_alerts(**kwargs)

Same as 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.

Args:

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 timeset

search: 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()

Returns a list with the fullpath to every log file used by nagios.

Lists are sorted by modification times. Newest logfile is at the front of the list so usually nagios.log comes first, followed by archivelogs

Returns:

List of strings
get_notifications(**kwargs)

Same as get_log_entries(), except return only notifications. Takes same parameters.

get_state_history(start_time=None, end_time=None, host_name=None, strict=True, service_description=None)

Returns a list of dicts, with the state history of hosts and services.

Args:

start_time: unix timestamp. if None, return all entries from today

end_time: If specified, only fetch log entries older than this (unix timestamp)

host_name: If provided, only return log entries that contain this string (case insensitive)

service_description: If provided, only return log entries that contain this string (case insensitive)

Returns:

List of dicts with state history of hosts and services
class pynag.Parsers.MultiSite(*args, **kwargs)

Bases: pynag.Parsers.Livestatus

Wrapps around multiple Livesatus instances and aggregates the results of queries.

Example:
>>> 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_backend(path, name)

Add a new livestatus backend to this instance.

Arguments:
path (str): Path to file socket or remote address name (str): Friendly shortname for this backend
get_backend(backend_name)

Return one specific backend that has previously been added

get_backends()

Returns a list of mk_livestatus instances

Returns:
list. List of mk_livestatus instances
get_contact(contact_name, backend=None)

Same as Livestatus.get_contact()

get_contactgroup(contactgroup_name, backend=None)

Same as Livestatus.get_contact()

get_host(host_name, backend=None)

Same as Livestatus.get_host()

get_hostgroup(hostgroup_name, backend=None)

Same as Livestatus.get_hostgroup()

get_service(host_name, service_description, backend=None)

Same as Livestatus.get_service()

get_servicegroup(servicegroup_name, backend=None)

Same as Livestatus.get_servicegroup()

query(query, *args, **kwargs)

Behaves like mk_livestatus.query() except results are aggregated from multiple backends

Arguments:
backend (str): If specified, fetch only data from this backend (see add_backend()) *args: Passed directly to mk_livestatus.query() **kwargs: Passed directly to mk_livestatus.query()
class pynag.Parsers.ObjectCache(cfg_file=None, strict=False)

Bases: pynag.Parsers.Config

Loads the configuration as it appears in objects.cache file

get_cfg_files()
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.RetentionDat(filename=None, cfg_file=None)

Bases: object

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.SshConfig(host, username, password=None, cfg_file=None)

Bases: pynag.Parsers.Config

Parse object configuration files from remote host via ssh

Uses python-paramiko for ssh connections.

access(*args, **kwargs)

Wrapper around os.access only, via ssh connection

add_to_tar(path)
exists(path)

Wrapper around os.path.exists only, via ssh connection

get_cfg_files()
is_cached(filename)
isdir(path)

Behaves like os.path.isdir only, via ssh connection

isfile(path)

Behaves like os.path.isfile only, via ssh connection

Behaves like os.path.islink only, via ssh connection

listdir(*args, **kwargs)

Wrapper around os.listdir but via ssh connection

open(filename, *args, **kwargs)

Behaves like file.open only, via ssh connection

Behaves like os.readlink only, via ssh connection

stat(*args, **kwargs)

Wrapper around os.stat only, via ssh connection

class pynag.Parsers.StatusDat(filename=None, cfg_file=None)

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)
get_contactstatus(contact_name)

Returns a dictionary derived from status.dat for one particular contact

Args:

contact_name: contact_name field of the contact’s status.dat data to parse and return as a dict.

Returns:

dict derived from status.dat for the contact.

Raises:

ValueError if object is not found

Example:

>>> 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

Args:

host_name: host_name field of the host’s status.dat data to parse and return as a dict.

Returns:

dict derived from status.dat for the host.

Raises:

ValueError if object is not found
get_servicestatus(host_name, service_description)

Returns a dictionary derived from status.dat for one particular service

Args:

service_name: service_name field of the host’s status.dat data to parse and return as a dict.

Returns:

dict derived from status.dat for the service.

Raises:

ValueError if object is not found
class pynag.Parsers.config(cfg_file=None, strict=False)

Bases: pynag.Parsers.Config

This class is here only for backwards compatibility. Use Config instead.

class pynag.Parsers.mk_livestatus(livestatus_socket_path=None, nagios_cfg_file=None, authuser=None)

Bases: pynag.Parsers.Livestatus

This class is here only for backwards compatibility. Use Livestatus instead.

class pynag.Parsers.object_cache(cfg_file=None, strict=False)

Bases: pynag.Parsers.ObjectCache

This class is here only for backwards compatibility. Use ObjectCache instead.

class pynag.Parsers.retention(filename=None, cfg_file=None)

Bases: pynag.Parsers.RetentionDat

This class is here only for backwards compatibility. Use RetentionDat instead.

class pynag.Parsers.status(filename=None, cfg_file=None)

Bases: pynag.Parsers.StatusDat

This class is here only for backwards compatibility. Use StatusDat instead.