Python调用Zabbix API获取主机列表的实现方法
本文介绍了如何利用Python调用Zabbix API获取主机信息。通过示例代码展示了host.get方法的参数配置,包括输出扩展、分组ID过滤及标志位筛选,并处理了可能的网络错误。该方法可复用获取其他数据,具体用法参考官方文档。
Zabbix的强大之处在于其完善的API接口,借助该接口可以获取Zabbix系统中的大部分数据。目前所需的数据基本都能通过API获取,以下提供了通过Python调用Zabbix API获取主机信息的代码示例。其他数据的获取方式与此类似,具体的API使用方法可参考官网文档:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import json
import urllib2
from urllib2 import URLError
from login import zabbix_login
t=zabbix_login()
def hostid_get():
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"groupids":14,
"filter":{"flags": "4" },
},
"auth":t.user_login(),
"id": 1,
})
request = urllib2.Request(t.url, data)
for key in t.header:
request.add_header(key, t.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
if hasattr(e, 'reason'):
print 'zabbix server is faile'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'zabbix server not request.'
print 'Error code: ', e.code
else:
response = json.loads(result.read())
result.close()
hostid=[]
hostname=[]
for host in response['result']:
hostid.append(host['hostid'])
hostname.append(host['name'])
return hostid,hostname
if __name__ == "__main__":
a,b=hostid_get()
i=0
n=len(b)
for i in range(n):
print a[i],b[i]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









