首页 > 编程语言 >python调用zabbix api接口实时展示数据

python调用zabbix api接口实时展示数据

时间:2023-08-11 15:03:26浏览次数:50  
标签:itemid python request json zabbix api result print ID


zabbix api接口来进行展示。经过思考之后,计划获取如下内容:
    1、  获得认证密钥     2、  获取zabbix所有的主机组
    3、  获取单个组下的所有主机
    4、  获取某个主机下的所有监控项
    5、  获取某个监控项的历史数据
    6、  获取某个监控项的最新数据

计划最后展示框架如下内容(这只是值方面,其它的会再加):
主机组1 ----主机名1---监控项1----当前值
                  ---监控项2----当前值
       ----主机名2----监控项1----当前值
                 ----监控项2----当前值
主机组2 ----主机名3---监控项1----当前值
                  ---监控项2----当前值
       ----主机名4----监控项1----当前值
                  ----监控项2----当前值

进入正题
1.     user.login方法获取zabbix server的认证结果官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/user/loginpython脚本:

[root@yang python]# cat auth.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"}
 # 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']


python脚本运行结果:


[root@yang python]# python auth.py
 Auth Successful. The Auth ID Is: a0b82aae0842c2041386a61945af1180

curl命令:


curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":
 "2.0","method":"user.login","params":{"user":"admin","password":"zabbix"},"auth":
 null,"id":0}' http://1.1.1.1/zabbix/api_jsonrpc.php

curl命令运行结果:


{"jsonrpc":"2.0","result":"b895ce91ba84fe247e444817c6773cc3","id":0}

2.     hostgroup.get方法获取所有主机组ID把认证密钥放到脚本中,每次获取数据时都需要认证。此处是获取zabbix server上的所有主机组名称与ID号。
官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/getpython脚本:


[root@yang python]# catget_hostgroup_list.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":"hostgroup.get",
    "params":{
        "output":["groupid","name"],
    },
    "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'])
    #print response
    for group in response['result']:
        print "Group ID:",group['groupid'],"\tGroupName:",group['name']

python脚本执行结果:


[root@yang python]# pythonget_hostgroup_list.py
 Number Of Hosts:  12
 Group ID: 11    Group Name: DB Schedule
 Group ID: 14    Group Name: DG-WY-KD-Server
 Group ID: 5     Group Name: Discovered hosts
 Group ID: 7     Group Name: Hypervisors
 Group ID: 2     Group Name: Linux servers
 Group ID: 8     Group Name: monitored_linux
 Group ID: 9     Group Name: qsmind
 Group ID: 12    Group Name: qssec
 Group ID: 13    Group Name: switch Group ID: 1     Group Name: Templates
 Group ID: 6     Group Name: Virtual machines
 Group ID: 4     Group Name: Zabbix servers

curl命令:


curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"hostgroup.get","params":{"output":["groupid","name"]},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php

curl执行结果:


{"jsonrpc":"2.0","result":[{"groupid":"11","name":"DBSchedule"},{"groupid":"14","name":"DG-WY-KD-Server"},{"groupid":"5","name":"Discoveredhosts"},{"groupid":"7","name":"Hypervisors"},{"groupid":"2","name":"Linuxservers"},{"groupid":"8","name":"monitored_linux"},{"groupid":"9","name":"qsmind"},{"groupid":"12","name":"qssec"},{"groupid":"13","name":"switch"},{"groupid":"1","name":"Templates"},{"groupid":"6","name":"Virtualmachines"},{"groupid":"4","name":"Zabbixservers"}],"id":0}

3.     host.get方法获取单个主机组下所有的主机ID。根据标题2中获取到的主机组id,把主机组id填入到下边脚本中,就可以获得该主机组下所有的主机id。
官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/host/getpython脚本:


[root@yang python]# cat get_group_one.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":"host.get",
    "params":{
        "output":["hostid","name"],
        "groupids":"14",
    },
    "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 ID:",host['hostid'],"HostName:",host['name']

python脚本执行结果:


[root@yang python]# pythonget_group_one.py  
 Number Of Hosts:  4
 Host ID: 10146 Host Name: DG-WY-KD-3F3B-00
 Host ID: 10147 Host Name: DG-WY-KD-3F3B-01
 Host ID: 10148 Host Name: DG-WY-KD-3F3B-02
 Host ID: 10149 Host Name: DG-WY-KD-3F3B-03

curl命令:


curl -i -X POST -H'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid","name"],"groupids":"14"},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' 
http://1.1.1.1/zabbix/api_jsonrpc.php

curl命令执行结果:


{"jsonrpc":"2.0","result":[{"hostid":"10146","name":"DG-WY-KD-3F3B-00"},{"hostid":"10147","name":"DG-WY-KD-3F3B-01"},{"hostid":"10148","name":"DG-WY-KD-3F3B-02"},{"hostid":"10149","name":"DG-WY-KD-3F3B-03"}],"id":0}

4.     itemsid.get方法获取单个主机下所有的监控项ID根据标题3中获取到的所有主机id与名称,找到你想要获取的主机id,获取它下面的所有items。
官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/itempython脚本:


[root@yang python]# cat get_items.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":"item.get",
    "params":{
        "output":["itemids","key_"],
        "hostids":"10146",
    },
    "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']

python脚本运行结果:


[root@yang python]# python get_items.py
 Number Of Hosts:  54
 {u'itemid': u'24986', u'key_':u'agent.hostname'}
 {u'itemid': u'24987', u'key_':u'agent.ping'}
 {u'itemid': u'24988', u'key_':u'agent.version'}
 {u'itemid': u'24989', u'key_':u'kernel.maxfiles'}
 {u'itemid': u'24990', u'key_':u'kernel.maxproc'}
 {u'itemid': u'25157', u'key_':u'net.if.in[eth0]'}
 {u'itemid': u'25158', u'key_':u'net.if.in[eth1]'}
 … …

curl命令:


curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"item.get","params":{"output":"itemids","hostids":"10146","search":{"key_":"net.if.out[eth2]"}},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php #此处加上了单个key的名称

curl命令执行结果:


{"jsonrpc":"2.0","result":[{"itemid":"25154"}],"id":0}

5.     history.get方法获取单个监控项的历史数据根据第4项的获取到的所有items id的值,找到想要监控的那项,获取它的历史数据。
官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/history/getpython脚本:


[root@yang python]# 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']

python脚本执行结果:


[root@yang python]# pythonget_items_history.py
 Number Of Hosts:  10
 {u'itemid': u'25159', u'ns': u'420722133',u'value': u'3008', u'clock': u'1410744079'}
 {u'itemid': u'25159', u'ns': u'480606614',u'value': u'5720', u'clock': u'1410744139'}
 {u'itemid': u'25159', u'ns': u'40905600',u'value': u'6144', u'clock': u'1410744200'}
 {u'itemid': u'25159', u'ns': u'175337062',u'value': u'2960', u'clock': u'1410744259'}
 {u'itemid': u'25159', u'ns': u'202705084',u'value': u'3032', u'clock': u'1410744319'}
 {u'itemid': u'25159', u'ns': u'263158421',u'value': u'2864', u'clock': u'1410744379'}
 {u'itemid': u'25159', u'ns': u'702285081',u'value': u'7600', u'clock': u'1410744439'}
 {u'itemid': u'25159', u'ns': u'231191890',u'value': u'3864', u'clock': u'1410744499'}
 {u'itemid': u'25159', u'ns': u'468566742',u'value': u'3112', u'clock': u'1410744559'}
 {u'itemid': u'25159', u'ns': u'421679098',u'value': u'2952', u'clock': u'1410744619'}
curl命令:
1
curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"history.get","params":{"history":3,"itemids":"25154","output":"extend","limit":10},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php
curl命令运行结果:
1
{"jsonrpc":"2.0","result":[{"itemid":"25154","clock":"1410744134","value":"4840","ns":"375754276"},{"itemid":"25154","clock":"1410744314","value":"5408","ns":"839852515"},{"itemid":"25154","clock":"1410744374","value":"7040","ns":"964558609"},{"itemid":"25154","clock":"1410744554","value":"4072","ns":"943177771"},{"itemid":"25154","clock":"1410744614","value":"8696","ns":"995289716"},{"itemid":"25154","clock":"1410744674","value":"6144","ns":"992462863"},{"itemid":"25154","clock":"1410744734","value":"6472","ns":"152634327"},{"itemid":"25154","clock":"1410744794","value":"4312","ns":"479599424"},{"itemid":"25154","clock":"1410744854","value":"4456","ns":"263314898"},{"itemid":"25154","clock":"1410744914","value":"8656","ns":"840460009"}],"id":0}

6.     history.get方法获取单个监控项最后的值只需把上个脚本中或curl中的limit参数改为1就可。


此时监控项的数据已拿到了,接下来的把它传给前台展示就行了。

标签:itemid,python,request,json,zabbix,api,result,print,ID
From: https://blog.51cto.com/u_6186189/7047947

相关文章

  • 商品详情接口设计:使用API调用获取淘宝商品数据的完整方案
    在如今的电商时代,获取商品的详细信息是实现商业化应用的基础。本文将详细介绍如何通过API调用来获取淘宝商品数据,并提供一个完整的商品详情接口设计方案,包括代码示例。开发人员可以根据此方案快速实现商品详情功能,提升用户体验。准备工作:在开始之前,我们需要确保已经申请并获得淘宝......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-11-playwright操作iframe-上篇
    1.简介原估计宏哥这里就不对iframe这个知识点做介绍和讲解了,因为前边的窗口切换就为这种网页处理提供了思路,另一个原因就是虽然iframe很强大,但是现在很少有网站用它了。但是还是有小伙伴或者童鞋们私下问这个问题,那么宏哥就单独写一篇关于iframe网页处理的文章。iframe是web自动......
  • 商品详情接口设计:使用API调用获取淘宝商品数据的完整方案
    ​在如今的电商时代,获取商品的详细信息是实现商业化应用的基础。本文将详细介绍如何通过API调用来获取淘宝商品数据,并提供一个完整的商品详情接口设计方案,包括代码示例。开发人员可以根据此方案快速实现商品详情功能,提升用户体验。准备工作:在开始之前,我们需要确保已经申请并获......
  • VS2019 C++ 调用python函数/类对象的方法
    1.环境配置VS工程配置要和python一致,安装的python如果是64位的,工程配置也要选成64位的在工程配置中添加包含目录和库目录,添加python环境目录里的include和libs文件夹路径。想要运行的keras-yolo3是在Anaconda中配置的环境,所以相应的文件夹路径可以在Anaconda的环境文件中......
  • linux python版本切换alternatives
    查看发现linux的python3命令指向alternativesalternatives是Linux系列操作系统的一个内置命令,即使最小化安装也有该命令,它的主要作用就是版本控制切换,比如,你的系统内有多个Python版本,Python3.8,Python2.7.5,Python3.6,。[root@santiagod-andibleopenstack-ansible]#find/usr/b......
  • Python打印类的属性
    一、使用__dict__打印类的属性classPerson:def__init__(self,name,age):self.name=nameself.age=ageperson=Person("Tom",18)print(person.__dict__)使用__dict__方法可以直接打印出类的属性及其对应的值。上述代码中,我们首先定义了一个Pe......
  • seamless-Immutable API(中文文档)
    seamless-Immutableseamless-Immutable是一套轻量级的持久化数据结构库,seamless-immutable并没有实现完整的PersistentDataStructure而是使用Object.defineProperty(因此只能在IE9及以上使用)扩展了JavaScript的Array和Object对象来实现,只支持Array和Object两种......
  • [数据分析与可视化] Python绘制数据地图5-MovingPandas绘图实例
    MovingPandas是一个基于Python和GeoPandas的开源地理时空数据处理库,用于处理移动物体的轨迹数据。关于MovingPandas的使用见文章:MovingPandas入门指北,本文主要介绍三个MovingPandas的绘图实例。MovingPandas官方仓库地址为:movingpandas。MovingPandas官方示例代码仓库地址为:movin......
  • python在抛出错误raise时,如何将相关信息一同携带出来(抛出自定义对象)?
    示例代码示例classMyClass(Exception):def__init__(self,info):self.info=infodefmy_method(self):print('MyClass.my_methodprintself.info:',self.info)try:raiseMyClass('错误信息')exceptMyClassase:......
  • 时序分析:Python 中的 ARIMA 模型
    推荐:使用NSDT场景编辑器快速助你搭建可二次编辑的3D应用场景什么是ARIMA模型?ARIMA模型是用于分析和预测时间序列数据的统计模型。ARIMA方法明确迎合了时间序列中的标准结构,为制作熟练的时间序列预测提供了一种简单而强大的方法。ARIMA代表自回归积分移动平均线。它结合了三......