一起来看一个Zabbix与RRDtool绘图篇之用ZabbixAPI取监控数据技巧文章,希望下文可以帮助到各位。 经过一个星期的死磕,Zabbix取数据和RRDtool绘图都弄清楚了,做第一运维平台的时候绘图取数据是直接从Zabbix的数据库取的,显得有点笨拙,不过借此也了解了Zabbix数据库结构还是有不少的收获。 学习Zabbix的API官方文档少不了,官方文档地址链接https://www.zabbix.com/documentation/ 大家选择对应的版本就好了,不过2.0版本的API手册位置有点特别开始我还以为没有,后来找到了如下https://www.zabbix.com/documentation/2.0/manual/appendix/api/api 用ZabbixAPI取监控数据的思路大致是这样的,先获取所有监控的主机,再遍历每台主机获取每台主机的所有图形,最后获取每张图形每个监控对象(item)的最新的监控数据或者一定时间范围的数据。 下面按照上面的思路就一段一段的贴出我的程序代码: 1、登录Zabbix获取通信token #!/usr/bin/env python #coding=utf-8 import json import urllib2 import sys ########################## class Zabbix: def __init__(self): self.url = "http://xxx.xxx.xxx.xxx:xxxxx/api_jsonrPC.php" self.header = {"Content-Type": "application/json"} self.authID = self.user_login() def user_login(self): data = http://www.3lian.com/edu/2015/02-27/json.dumps({ "jsonrPC": "2.0", "method": "user.login", "params": {"user": "用户名", "passWord": "密码"}, "id": 0}) request = urllib2.Request(self.url,data) for key in self.header: request.add_header(key,self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Auth Failed, Please Check Your Name And PassWord:",e.code else: response = json.loads(result.read()) result.close() authID = response['result'] return authID ##################通用请求处理函数#################### def get_data(self,data,hostip=""): request = urllib2.Request(self.url,data) for key in self.header: request.add_header(key,self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason elif hasattr(e, 'code'): print 'The server could not fulfill the request.' print 'Error code: ', e.code return 0 else: response = json.loads(result.read()) result.close() return response 2、获取所有主机 ##################################################################### #获取所有主机和对应的hostid def hostsid_get(self): data = http://www.3lian.com/edu/2015/02-27/json.dumps({ "jsonrPC": "2.0", "method": "host.get", "params": { "output":["hostid","status","host"]}, "auth": self.authID, "id": 1}) res = self.get_data(data)['result'] #可以返回完整信息 #return res hostsid = [] if (res != 0) and (len(res) != 0): for host in res: if host['status'] == '1': hostsid.append({host['host']:host['hostid']}) elif host['status'] == '0': hostsid.append({host['host']:host['hostid']}) else: pass return hostsid 返回的结果是一个列表,每个元素是一个字典,字典的key代表主机名,value代表hostid 3、获取每台主机的每张图形 ################################################################### #查找一台主机的所有图形和图形id def hostgraph_get(self, hostname): data = http://www.3lian.com/edu/2015/02-27/json.dumps({ "jsonrPC": "2.0", "method": "host.get", "params": { "selectGraphs": ["graphid","name"], "filter": {"host": hostname}}, "auth": self.authID, "id": 1}) res = self.get_data(data)['result'] #可以返回完整信息rs,含有hostid |