Zabbix与RRDtool绘图篇(1)_用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
1#!/usr/bin/env python
2#coding=utf-8
3import json
4import urllib2
5import sys
6##########################
7class Zabbix:
8 def __init__(self):
9 self.url = "http://xxx.xxx.xxx.xxx:xxxxx/api_jsonrpc.php"
10 self.header = {"Content-Type": "application/json"}
11 self.authID = self.user_login()
12 def user_login(self):
13 data = json.dumps({
14 "jsonrpc": "2.0",
15 "method": "user.login",
16 "params": {"user": "用户名", "password": "密码"},
17 "id": 0})
18 request = urllib2.Request(self.url,data)
19 for key in self.header:
20 request.add_header(key,self.header[key])
21 try:
22 result = urllib2.urlopen(request)
23 except URLError as e:
24 print "Auth Failed, Please Check Your Name And Password:",e.code
25 else:
26 response = json.loads(result.read())
27 result.close()
28 authID = response['result']
29 return authID
30 ##################通用请求处理函数####################
31 def get_data(self,data,hostip=""):
32 request = urllib2.Request(self.url,data)
33 for key in self.header:
34 request.add_header(key,self.header[key])
35 try:
36 result = urllib2.urlopen(request)
37 except URLError as e:
38 if hasattr(e, 'reason'):
39 print 'We failed to reach a server.'
40 print 'Reason: ', e.reason
41 elif hasattr(e, 'code'):
42 print 'The server could not fulfill the request.'
43 print 'Error code: ', e.code
44 return 0
45 else:
46 response = json.loads(result.read())
47 result.close()
48 return response
2、获取所有主机
1#####################################################################
2 #获取所有主机和对应的hostid
3 def hostsid_get(self):
4 data = json.dumps({
5 "jsonrpc": "2.0",
6 "method": "host.get",
7 "params": { "output":["hostid","status","host"]},
8 "auth": self.authID,
9 "id": 1})
10 res = self.get_data(data)['result']
11 #可以返回完整信息
12 #return res
13 hostsid = []
14 if (res != 0) and (len(res) != 0):
15 for host in res:
16 if host['status'] == '1':
17 hostsid.append({host['host']:host['hostid']})
18 elif host['status'] == '0':
19 hostsid.append({host['host']:host['hostid']})
20 else:
21 pass
22 return hostsid
返回的结果是一个列表,每个元素是一个字典,字典的key代表主机名,value代表hostid
3、获取每台主机的每张图形
1###################################################################
2 #查找一台主机的所有图形和图形id
3 def hostgraph_get(self, hostname):
4 data = json.dumps({
5 "jsonrpc": "2.0",
6 "method": "host.get",
7 "params": { "selectGraphs": ["graphid","name"],
8 "filter": {"host": hostname}},
9 "auth": self.authID,
10 "id": 1})
11 res = self.get_data(data)['result']
12 #可以返回完整信息rs,含有hostid
13 return res[0]['graphs']
注意传入的参数是主机名而不是主机id,结果也是由字典组成的列表。
4、获取每张图的监控对象item
1#可以返回完整信息rs,含有hostid
2 tmp = res[0]['items']
3 items = []
4 for value in tmp:
5 if '$' in value['name']:
6 name0 = value['key_'].split('[')[1].split(']')[0].replace(',', '')
7 name1 = value['name'].split()
8 if 'CPU' in name1:
9 name1.pop(-2)
10 name1.insert(1,name0)
11 else:
12 name1.pop()
13 name1.append(name0)
14 name = ' '.join(name1)
15 tmpitems = {'itemid':value['itemid'],'delay':value['delay'],'units':value['units'],'name':name,'value_type':value['value_type'],'lastclock':value['lastclock'],'lastvalue':value['lastvalue']}
16 else:
17 tmpitems = {'itemid':value['itemid'],'delay':value['delay'],'units':value['units'],'name':value['name'],'value_type':value['value_type'],'lastclock':value['lastclock'],'lastvalue':value['lastvalue']}
18 items.append(tmpitems)
19 return items
返回的数据已经包含了最新的一次监控数据的值和取值的时间戳,如果只需要取最新的监控数据,到这里其实就可以了,记得这次传入的参数是graphid。
5、根据itemid取得更多的监控数据
下面是取10条监控数据,可以任意更改参数获取更多的数据,全凭自己所需了。
1################################################################
2 #获取历史数据,history必须赋值正确的类型0,1,2,3,4 float,string,log,integer,text
3 def history_get(self, itemid, i):
4 data = json.dumps({
5 "jsonrpc": "2.0",
6 "method": "history.get",
7 "params": { "output": "extend",
8 "history": i,
9 "itemids": itemid,
10 "sortfield": "clock",
11 "sortorder": "DESC",
12 "limit": 10},
13 "auth": self.authID,
14 "id": 1})
15 res = self.get_data(data)['result']
16 return res
上面的所有代码加起来就是一个Zabbix取数据的类。取出来的数据可以用RRDtool绘图或做其它用途了。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/zabbix-rrdtool-1/4102.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.