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


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


Remove configuration files that have no configuration items


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=””)

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


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” )
String of the first value found for
>>> 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


Returns a list of all discovered object types


Get a single resource value which can be located in any resource.cfg file

resource_name: Name as it appears in resource file (i.e. $USER1$)
String value of the resource value.
  • KeyError if resource is not found
  • ParserError if resource is not found and you do not have permissions

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


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

None if nagios binary was not found

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

Wrapper around os.path.islink

item_add(item, filename)

Adds a new object to a specified config file

item – Item to be created filename – Filename that we are supposed to write to
True on success
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=””)
True on success
ValueError if object is not found IOError if save fails

Delete one specific item from its configuration files

item – Item that is to be rewritten str_new_item – str representation of the new item
item_rewrite( item, “define service {

name example-service register 0 }

” )
True on success
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” )
True on success
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”)
True on success
ValueError if object is not found IOError if save fails
item_rewrite(item, str_new_item)

Completely rewrites item with string provided.

item – Item that is to be rewritten str_new_item – str representation of the new item
item_rewrite( item, “define service {

name example-service register 0 }

” )
True on success
ValueError if object is not found IOError if save fails

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

open(filename, *args, **kwargs)

Wrapper around global open()

parse(*args, **kw)

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

string – A string containing one or more object definitions filename (optional) – If filename is provided, it will be referenced when raising exceptions
>>> 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
A list of dictionaries, that look like

Return a string that can be used in a configuration file

Wrapper around os.readlink

remove(*args, **kwargs)

Wrapper around os.remove

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

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


# cat /etc/nagios/plugins.ini [main] host_name = localhost [other section] host_name = # 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 0x7fa7ebfb23f0>)

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

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

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

Results are in the form of:
‘key’: [“possible”,”values”]


getlist(option_name, default=<object object at 0x7fa7ebfb23f0>)

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.

Example the following the file:
[main] name = this is a name key = value key = value2
Would return:
‘name’: [‘this is a name’], ‘key’: [value, value2]


}, ]


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']
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,))

get_contactgroups(*args, **kwargs)
get_contacts(*args, **kwargs)
get_hostgroups(*args, **kwargs)
get_hosts(*args, **kwargs)
get_service(host_name, service_description)
get_servicegroups(*args, **kwargs)
get_services(*args, **kwargs)
query(query, *args, **kwargs)

Raises ParserError if there are problems communicating with livestatus socket

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 Livestatus log output


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

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


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, strict=True, service_description=None)

Returns a list of dicts, with the state history of hosts and services. Parameters behaves similar to get_log_entries

class pynag.Parsers.MultiSite(*args, **kwargs)

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='', name='remote')
add_backend(path, name)

Add a new livestatus backend to this instance.

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

Return one specific backend that has previously been added


Returns a list of mk_livestatus instances

list. List of mk_livestatus instances
get_contact(contact_name, backend)

Same as Livestatus.get_contact()

get_contactgroup(contactgroup_name, backend)

Same as Livestatus.get_contact()

get_host(host_name, backend)

Same as Livestatus.get_host()

get_hostgroup(hostgroup_name, backend)

Same as Livestatus.get_hostgroup()

get_service(host_name, service_description, backend)

Same as Livestatus.get_service()

get_servicegroup(servicegroup_name, backend)

Same as Livestatus.get_servicegroup()

query(query, *args, **kwargs)

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

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

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

Example Usage: >>> #r = retention() >>> #r.parse() >>> #print r >>> #print[‘info’]


Parses your status.dat file and stores in a dictionary under

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

access(*args, **kwargs)

Wrapper around os.access


Wrapper around os.path.exists


Behaves like os.path.isdir


Behaves like os.path.isfile

Behaves like os.path.islink

open(filename, *args, **kwargs)

Behaves like os.readlink

stat(*args, **kwargs)

Wrapper around os.stat

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 Example usage: >>> s = status() >>> s.parse() >>> keys = >>> ‘info’ in keys True >>> ‘programstatus’ in keys True >>> for service in‘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

ValueError if object is not found
>>> s = status()
>>> s.get_contactstatus(contact_name='invalid_contact')
>>> first_contact =['contactstatus'][0]['contact_name']
>>> s.get_contactstatus(first_contact)['contact_name'] == first_contact

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

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

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

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.