Skip to content

Instantly share code, notes, and snippets.

@micw
Created June 1, 2016 18:52
Show Gist options
  • Select an option

  • Save micw/45b4169f3d2bb6edfe577ac488c9762a to your computer and use it in GitHub Desktop.

Select an option

Save micw/45b4169f3d2bb6edfe577ac488c9762a to your computer and use it in GitHub Desktop.
Simple nagios check that reads a json via http and converts it's output to a nagios check result
#!/usr/bin/python
#
'''
This script reads a JSON from an URL and converts it to nagios-plugin output.
The JSON must be in the following format (See https://nagios-plugins.org/doc/guidelines.html#AEN78
for Details about min/max/warn/crit values and units:
{
status: 'OK'|'WARNING'|'CRITICAL',
message: 'any text not containing single quote',
metrics: [ // optional
{
name: 'MetricName',
value: 12345.67,
unit: optional unit,
min: optional min value,
max: optional max value,
warn: optional warning threshold,
crit: optional critical threshold,
},
{ ... }
]
}
'''
import sys
import urllib3
import simplejson
ST_OK=0
ST_WARN=1
ST_CRIT=2
def main():
args=sys.argv
# args=["","http://crawler1.jenkins.evermind.de:8080/service/status/DE_IMMOSCOUT24"]
if (len(args)!=2):
print("CRITICAL: Missing argument: URL")
sys.exit(ST_CRIT)
url=args[1]
http = urllib3.PoolManager()
try:
req = http.request("GET",url)
except (ConnectionRefusedError,urllib3.exceptions.MaxRetryError):
print("CRITICAL: Unable to connect to "+url)
sys.exit(ST_CRIT)
if (req.status!=200):
print("CRITICAL: Got HTTP-Status "+str(req.status))
sys.exit(ST_CRIT)
try:
json=simplejson.loads(req.data)
except (TypeError,UnicodeDecodeError):
print("CRITICAL: Unable to parse json: "+str(req.data))
sys.exit(ST_CRIT)
metrics=""
if ('metrics' in json and hasattr(json['metrics'], '__iter__')):
metrics+=" |"
for metric in json['metrics']:
metrics+=" '"+metric['name']+"'"
metrics+="="+str(metric['value'])
if ('unit' in json):
metrics+=metric['unit']
metrics+=';'
if ('warn' in json):
metrics+=int(metric['warn'])
metrics+=';'
if ('crit' in json):
metrics+=int(metric['crit'])
metrics+=';'
if ('min' in json):
metrics+=int(metric['min'])
metrics+=';'
if ('max' in json):
metrics+=int(metric['max'])
if ('status' not in json):
print("CRITICAL: Invalid json: "+simplejson.dumps(json))
sys.exit(ST_CRIT)
print(json['message']+metrics)
if (json['status']=='OK'):
sys.exit(ST_OK)
if (json['status']=='WARNING'):
sys.exit(ST_WARN)
sys.exit(ST_CRIT)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment