A-A+
使用python通过zabbix API获取后台历史数据
对于zabbix自身web所展示的数据,其实官方给出了很多其他方式获取数据的方式:
比如说用过zabbix_get -k 加key 获取value 这种是主动请求数据
也可以客户端zabbix_send发送数据
或者通过web API的方式。zabbix本身提供了一个api交互的页面 api_jsonrpc.php。
下面我简单介绍几个:
一、首先肯定显示登陆。我们所有基于api操作都需要先登录认证,然后成功后会返回一个authid。然后后续的接口只需要通过authid来做各种查询即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
method=user.login方法获取zabbix server的认证结果官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/user/login [root@localhost python]# cat zabbix_auth.py #!/usr/bin/env python2.7 #coding=utf-8 import json import urllib2 # based url and required header url = "http://ip地址/zabbix/api_jsonrpc.php" header = {"Content-Type":"application/json"} # auth user and password data = json.dumps( { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 0 }) # create request object request = urllib2.Request(url,data) for key in header: request.add_header(key,header[key]) # auth and get authid try: result = urllib2.urlopen(request) except URLError as e: print "Auth Failed, Please Check Your Name AndPassword:",e.code else: response = json.loads(result.read()) result.close() print"Auth Successful. The Auth ID Is:",response['result'] |
二、通过history_get来获取历史记录
history.get方法获取单个监控项的历史数据根据第4项的获取到的所有items id的值,找到想要监控的那项,获取它的历史数据。
官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/history/get
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
catget_items_history.py #!/usr/bin/env python2.7 #coding=utf-8 import json import urllib2 # based url and required header url = "http://1.1.1.1/zabbix/api_jsonrpc.php" header = {"Content-Type":"application/json"} # request json data = json.dumps( { "jsonrpc":"2.0", "method":"history.get", "params":{ "output":"extend", "history":3, "itemids":"25159", "limit":10 }, "auth":"3c0e88885a8cf8af9502b5c850b992bd", # theauth id is what auth script returns, remeber it is string "id":1, }) # create request object request = urllib2.Request(url,data) for key in header: request.add_header(key,header[key]) # get host list 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 else: response = json.loads(result.read()) result.close() print "Number Of Hosts: ", len(response['result']) for host in response['result']: print host #print "Host ID:",host['hostid'],"HostName:",host['name'] |