1、身份验证
任何Zabbix API客户端在真正工作之前都需要验证它自身。在这里是采用User.login方法。这个方法接受一个用户名和密码作为参数并返回验证ID,一个安全哈希串用于持续的API调用(在使用User.logout之前该验证ID均有效)。具体Python代码auth.py如下:
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://192.168.120.128/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": "123456"
},
"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 And Password:",e.code
else:
response = json.loads(result.read())
result.close()
print "Auth Successful. The Auth ID Is:",response['result']
2、获取监控主机列表
这段脚本需要采用auth.py中获取的验证ID并执行host.get方法来获取主机列表。来看具体代码get_host.py:
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://192.168.120.128/api_jsonrpc.php"
header = {"Content-Type": "application/json"}
# request json
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"host.get",
"params":{
"output":["hostid","name"],
"filter":{"host":""}
},
"auth":"179242a2e0e61873c81afb3e721c5605",
"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'],"Host Name:",host['name']