Skip to content

Instantly share code, notes, and snippets.

@ravnx
Forked from alexwright/status2json.py
Last active August 20, 2022 18:46
Show Gist options
  • Save ravnx/5e7b2bf3e5b69e97641fac2bef8ac131 to your computer and use it in GitHub Desktop.
Save ravnx/5e7b2bf3e5b69e97641fac2bef8ac131 to your computer and use it in GitHub Desktop.
Parse the Nagios status.dat and poop out some JSON
#!/usr/bin/python3
"""
This script will dump host stats from your Nagios4 status.dat as JSON.
You can put this in your /usr/lib/cgi-bin/nagios4 directory and chmod +x this file,
then, to access it remotely use python requests:
r = requests.get('https://nagiosinstall-location.com/nagios4/cgi-bin/status2json.py', auth=HTTPDigestAuth(user,pass))
print(r.json())
You might need to add .py to your http.conf cgi handlers.
Right now I output this JSON:
[
'Server-Name':
{ 'state': 'UP'
'plugin_output': 'PING OK - Packet loss = 0%, RTA = 8.85 ms'
}
]
Forked from @alexwright
"""
import re
import json
STATUS_FILE_PATH = "/var/lib/nagios4/status.dat"
def read_status():
hosts = {}
services = {}
fh = open(STATUS_FILE_PATH)
status_raw = fh.read()
pattern = re.compile('([\w]+)\s+\{([\S\s]*?)\}',re.DOTALL)
matches = pattern.findall(status_raw)
for def_type, data in matches:
lines = [line.strip() for line in data.split("\n")]
pairs = [line.split("=", 1) for line in lines if line != '']
data = dict(pairs)
if def_type == "servicestatus":
services[data['service_description']] = data
if 'host_name' in data:
hosts[data['host_name']]['services'].append(data)
if def_type == "hoststatus":
data['services'] = []
hosts[data['host_name']] = data
return {
'hosts': hosts,
'services': services,
}
if __name__ == "__main__":
data = read_status()
# Readable state table, I'm just displaying it, so dont want integers.
STATE = { '0': 'UP',
'1': 'DOWN',
'2': 'UNREACHABLE',
}
hoststats = []
for d in data.get('hosts'):
plugin_output = data.get('hosts').get(d).get('plugin_output')
current_state = data.get('hosts').get(d).get('current_state')
state = STATE[current_state]
this_status = { d: { 'state': state, 'plugin_output': plugin_output }}
hoststats.append(this_status)
print("Content-Type: application/json;charset=utf-8\n")
print(json.dumps(hoststats))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment