#!/usr/bin/env python # # Authors: # rafael@postgresql.org.es / http://www.postgresql.org.es/ # # Copyright (c) 2014 USIT-University of Oslo import sys import os import time import json import urllib2 import xml.etree.ElementTree as ET # ############################################ # Method: generate_json_output # # Parameters: Text = temperature box hostname # Returns: JSON data # ############################################ def generate_json_output(temperature_box): ''' Generate the json output needed by Zabbix to define a "low level discovery rule". We use the macro {#DEVICEID} in the output to identify a temperature device. This macro is the one to use when defining a "low level discovery rule" that discovery temperature devices in a temperature box. More information: https://www.zabbix.com/documentation/2.2/manual/discovery/low_level_discovery ''' try: minutes_since_last_update = 0 temp_file = '/tmp/' + temperature_box + '_temperature_data.xml' if os.path.exists(temp_file) == True: minutes_since_last_update = (time.time() - os.path.getmtime(temp_file)) / 60 # # Get the XML data from # http:///data.xml only if the local # temp file with the XML code does not exist or if the file is # older that 5 minutes. # if os.path.exists(temp_file) == False or minutes_since_last_update > 5: req = urllib2.Request('http://' + temperature_box + '/data.xml') response = urllib2.urlopen(req,timeout=5) the_page = response.read() with open (temp_file,'w') as xmlfile: xmlfile.write(the_page) tree = ET.parse(temp_file) root = tree.getroot() except Exception as e: print e sys.exit(1) try: # # Get the list with all devices in this temperature box and # return the JSON data needed by Zabbix low-level # autodiscovery # device_list = [] for child in root.findall("./devices/device"): device = {} device = {"{#DEVICEID}": child.attrib['id'],"{#DEVICENAME}": child.attrib['name']} device_list.append(device) result = {"data":device_list} print json.dumps(result,sort_keys=True,indent=2) except Exception as e: print e sys.exit(1) # ############################################ # MAIN # ############################################ if __name__ == '__main__': try: if len(sys.argv) == 2: temperature_box = sys.argv[1].lower() generate_json_output(temperature_box) else: print "Error: Wrong number of parameters" print 'Format: ' + sys.argv[0] + ' ' sys.exit(1) except Exception as e: print e sys.exit(1)