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

简介:

    近日公司准备自已做一个运维管理平台,其中的监控部分,打算调用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/login

python脚本:

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
[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脚本运行结果:

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

curl命令:

1
2
3
curl  - - X POST  - '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命令运行结果:

1
{ "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/get

python脚本:

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
[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脚本执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[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命令:

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

curl执行结果:

1
{ "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/get

python脚本:

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
[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脚本执行结果:

1
2
3
4
5
6
[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命令:

1
2
curl  - - X POST  - H 'Content-Type: application/json'  - '{"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命令执行结果:

1
{ "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/item

python脚本:

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
[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脚本运行结果:

1
2
3
4
5
6
7
8
9
10
[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命令:

1
2
curl  - - X POST  - 'Content-Type:application/json'  - '{"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命令执行结果:

1
{ "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/get

python脚本:

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
[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脚本执行结果:

1
2
3
4
5
6
7
8
9
10
11
12
[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  - - X POST  - 'Content-Type:application/json'  - '{"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就可。



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





     本文转自杨云1028 51CTO博客,原文链接:http://blog.51cto.com/yangrong/1559123,如需转载请自行联系原作者




相关文章
|
1天前
|
机器学习/深度学习 数据可视化 vr&ar
|
2天前
|
数据可视化 数据挖掘 Python
数据界的颜值担当!Python数据分析遇上Matplotlib、Seaborn,可视化美出新高度!
【7月更文挑战第24天】在数据科学领域,Python的Matplotlib与Seaborn将数据可视化升华为艺术,提升报告魅力。Matplotlib作为基石,灵活性强,新手友好;代码示例展示正弦波图的绘制与美化技巧。Seaborn针对统计图表,提供直观且美观的图形,如小提琴图,增强数据表达力。两者结合,创造视觉盛宴,如分析电商平台销售数据时,Matplotlib描绘趋势,Seaborn揭示类别差异,共塑洞察力强的作品,使数据可视化成为触动人心的艺术。
22 7
|
3天前
|
数据采集 Web App开发 存储
Python-数据爬取(爬虫)
【7月更文挑战第24天】
30 7
|
1天前
|
机器学习/深度学习 数据采集 算法
数据海洋中的导航者:Scikit-learn库引领Python数据分析与机器学习新航向!
【7月更文挑战第26天】在数据的海洋里,Python以强大的生态成为探索者的首选,尤其Scikit-learn库(简称sklearn),作为一颗璀璨明珠,以高效、灵活、易用的特性引领数据科学家们破浪前行。无论新手还是专家,sklearn提供的广泛算法与工具支持从数据预处理到模型评估的全流程。秉承“简单有效”的设计哲学,它简化了复杂模型的操作,如线性回归等,使用户能轻松比较并选择最优方案。示例代码展示了如何简洁地实现线性回归分析,彰显了sklearn的强大能力。总之,sklearn不仅是数据科学家的利器,也是推动行业进步的关键力量。
|
4天前
|
缓存 自然语言处理 搜索推荐
解析微店商品详情的 API 接口获取之道
在电商蓬勃发展的时代,微店的商品详情数据对商家与开发者极具价值。API接口成为挖掘这些数据的关键,助力商家洞察市场,优化策略,实时监控竞品,管理库存;赋能开发者创新,如构建推荐系统和分析工具。获取接口需注册认证,理解政策,明确权限需求。调用API须精读文档,选用合适语言编码,处理错误,优化策略如缓存和异步请求。数据处理涉及自然语言分析、价格预测和情感分析,应用广泛。注意事项包括合规操作、数据安全、适应接口变动及性能优化,确保高效合法利用数据,推动电商进步。
|
4天前
|
数据可视化 数据挖掘 开发者
数据可视化新纪元!Python + Matplotlib + Seaborn,让你的数据故事生动起来!
【7月更文挑战第23天】在数据驱动时代,Python通过Matplotlib与Seaborn引领数据可视化新纪元。Matplotlib基础强大,提供广泛绘图选项;Seaborn则简化流程,图表更美观,适合快速可视化。两者结合,轻松应对复杂定制需求,将数据转化为生动故事,支持决策与交流。
18 6
|
4天前
|
API 数据安全/隐私保护 开发者
Web 开发新风尚!Python RESTful API 设计与实现,让你的接口更懂开发者心!
【7月更文挑战第23天】Python的RESTful API设计在Web开发中流行,提升效率与体验。REST强调HTTP方法(GET, POST, PUT, DELETE)操作资源。使用Flask框架可快速实现API,如管理用户信息。示例代码展示如何创建、读取、更新和删除用户,通过不同HTTP方法和URL路径。实际应用中,增加验证、错误处理和权限控制可增强API的安全性和稳定性。安装Flask后,可运行代码测试API功能。
24 6
|
3天前
|
数据采集 机器学习/深度学习 算法
Python-数据爬取(爬虫)
【7月更文挑战第23天】
25 5
|
2天前
|
数据可视化 数据挖掘 Python
|
4天前
|
安全 API 网络安全
​邮箱OTP认证验证API发送邮件接口
**摘要 (Markdown格式):** OTP认证增强在线服务安全,尤其适用于邮箱验证。AOKSend提供邮箱OTP验证API,实现安全的邮件发送和用户身份验证。关键优势包括提高安全性、简化用户体验、实时发送、可扩展性和多层安全。配置涉及生成API密钥、设置SMTP、实现OTP逻辑、发送邮件及验证。AOKSend的分析工具帮助优化策略,适合各规模企业。

推荐镜像

更多