From d8a7c626ea9fd7ccd4f755c89edfcb31dddf6fee Mon Sep 17 00:00:00 2001 From: Oliver Ladner Date: Fri, 21 Dec 2018 09:34:07 +0100 Subject: [PATCH] JSON check boilerplate --- check_json.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100755 check_json.py diff --git a/check_json.py b/check_json.py new file mode 100755 index 0000000..42f8fdc --- /dev/null +++ b/check_json.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +import getopt +import requests +import json +import sys + +goodstate = 'UP' +icinga_ok = 0 +icinga_crit = 2 +icinga_unknown = 3 + +try: + options, args = getopt.getopt(sys.argv[1:], 'u:t:', ['url=', 'timeout=',]) +except getopt.GetoptError as e: + print e + sys.exit(icinga_crit) + +for opt, arg in options: + if opt in ('-u', '--url'): + url = arg + elif opt in ('-t', '--timeout'): + timeout_s = int(arg) + else: + sys.exit(1) + +try: + resp = requests.get(url, timeout=timeout_s) +except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as e: + print e + sys.exit(icinga_crit) + +try: + json_resp = json.loads(resp.text) +except ValueError as e: + print e + sys.exit(icinga_crit) + +http_status = resp.status_code +state_global = json_resp['status'] + +if (state_global == goodstate and + http_status == requests.codes.ok): + # 'OK' case + print 'All is fine (status: ' + state_global + ', HTTP: ' + str(http_status) + ')' + sys.exit(icinga_ok) +elif (state_global != goodstate or + http_status != requests.codes.ok): + # 'NOK' case + print 'Global state is bad (status: ' + state_global + ', HTTP: ' + str(http_status) + '). Check ' + url + sys.exit(icinga_crit) +else: + # 'unknown' case + print 'Undefined state. Check other monitoring tools for evidence' + sys.exit(icinga_unknown)