231321 发表于 2016-3-21 10:04:26

zabbix 二次开发之调用api接口获取历史数据

前面一篇写了数据同步和模板绑定,zabbix其实能做的事还蛮多。
    zabbix提供了一个非常好的前端展示页面,但是我们总觉得不太好看;我们可以进一步调用他的api通过获取每一个监控项的历史数据,然后打到我们的监控平台上;主流的有rrdtool方式和highcharts方式;rrdtool略显复杂,还要学习rrdtool之类的几个聚合方式。相对而言我更喜欢highcharts的方式,出图简便,只需要提供数据和时间戳组成的json数据就够了,之前也介绍过具体;那么这里我们先拿出我们想要的数据。

    zabbix的api读取方式如下:
    1、通过post方式传入用户名密码获取token秘钥。
    2、获取所有主机的hostid和name。
    3、通过hostid获取每个监控项目的item和对应的key。
    4、通过传入的itemid获取相对应的历史数据。

以上步骤都是需要传入token才能执行操作,pipy已经提供了第三方插件,让我们省去了这一部分的操作;具体参考:https://pypi.python.org/pypi/zabbix-client/0.1.1;zabbix api文档请参考官方文档。


1、获取主机的代码:

1
2
3
4
5
6
    def get_hosts(self):
      data = {
      "output": ["hostid", "name"]
      }
      ret = self.zb.host.get(**data)
      return ret




执行结果:


2、获取每个主机对应的监控项和监控项具体名称:

1
2
3
4
5
6
7
   def item_get(self, hostids="10109"):
            data = {
         "output":["itemids","key_"],
         "hostids": hostids,
            }
            ret = self.zb.item.get(**data)
            return ret




执行结果:



3、获取对应的历史数据:

1
2
3
4
5
6
7
8
9
10
    def history_get(self, itemid, i ,limit=10):
      data = { "output": "extend",
          "history": i,
          "itemids": itemid,
          "sortfield": "clock",
          "sortorder": "DESC",
          "limit": limit
          }
      ret = self.zb.history.get(**data)
      return ret








具体代码:

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
from zabbix_client import ZabbixServerProxy
class Zabbix():
    def __init__(self):
      self.zb = ZabbixServerProxy("http://192.168.10.100/zabbix")
      self.zb.user.login(user="Admin", password="zabbix")
    def get_hosts(self):
      data = {
      "output": ["hostid", "name"]
      }
      ret = self.zb.host.get(**data)
      return ret
    def item_get(self, hostids="10109"):
      data = {
       "output":["itemids","key_"],
       "hostids": hostids,
      }
      ret = self.zb.item.get(**data)
      return ret
    def history_get(self, itemid, i ,limit=10):
    ###history参数中有0,1,2,3,4表示:float,string,log,integer,text
      data = { "output": "extend",
          "history": i,
          "itemids": itemid,
          "sortfield": "clock",
          "sortorder": "DESC",
          "limit": limit
          }
      ret = self.zb.history.get(**data)
      return ret
if __name__ == "__main__":
    zabbix_server = Zabbix()
#    print zabbix_server.get_hosts()
    print zabbix_server.history_get("24519",3)



页: [1]
查看完整版本: zabbix 二次开发之调用api接口获取历史数据