4 # rafael@postgresql.org.es / http://www.postgresql.org.es/
6 # Copyright (c) 2014 USIT-University of Oslo
13 import xml.etree.ElementTree as ET
15 # ############################################
16 # Method: generate_json_output
18 # Parameters: Text = temperature box hostname
20 # ############################################
22 def generate_json_output(temperature_box):
25 Generate the json output needed by Zabbix to define a "low level
28 We use the macro {#DEVICEID} in the output to identify a
29 temperature device. This macro is the one to use when defining a
30 "low level discovery rule" that discovery temperature devices in a
34 https://www.zabbix.com/documentation/2.2/manual/discovery/low_level_discovery
39 minutes_since_last_update = 0
40 temp_file = '/tmp/' + temperature_box + '_temperature_data.xml'
42 if os.path.exists(temp_file) == True:
43 minutes_since_last_update = (time.time() - os.path.getmtime(temp_file)) / 60
46 # Get the XML data from
47 # http://<temperature_box_hostname>/data.xml only if the local
48 # temp file with the XML code does not exist or if the file is
49 # older that 5 minutes.
52 if os.path.exists(temp_file) == False or minutes_since_last_update > 5:
54 req = urllib2.Request('http://' + temperature_box + '/data.xml')
55 response = urllib2.urlopen(req,timeout=5)
56 the_page = response.read()
58 with open (temp_file,'w') as xmlfile:
59 xmlfile.write(the_page)
61 tree = ET.parse(temp_file)
64 except Exception as e:
71 # Get the list with all devices in this temperature box and
72 # return the JSON data needed by Zabbix low-level
78 for child in root.findall("./devices/device"):
80 for device_enable in root.findall("./alarms/alarm"):
81 if device_enable.attrib['device-id'] == child.attrib['id'] \
82 and device_enable.attrib['field'] == 'TempC' \
83 and int(device_enable.attrib['enabled']) > 0:
86 device = {"{#DEVICEID}": child.attrib['id'],"{#DEVICENAME}": child.attrib['name']}
88 device_list.append(device)
90 result = {"data":device_list}
91 print json.dumps(result,sort_keys=True,indent=2)
93 except Exception as e:
98 # ############################################
100 # ############################################
102 if __name__ == '__main__':
105 if len(sys.argv) == 2:
106 temperature_box = sys.argv[1].lower()
107 generate_json_output(temperature_box)
110 print "Error: Wrong number of parameters"
111 print 'Format: ' + sys.argv[0] + ' <temperature box hostname>'
114 except Exception as e: