zabbix监控程序有一个API接口,可以调用这些接口来自动添加主机,查询zabbix中监控的主机,监控的模板、监控的主机组等信息。
下面分享的这例python代码,就是调用zabbix的API接口来实现以上功能的。
例子:
复制代码 代码示例:
#!/usr/bin/env python
#edit: www.jb200.com
#
# -*- coding: utf-8 -*-
import json
import urllib2
import sys
class zabbixtools:
def __init__(self):
self.url = "http://192.168.11.186/zabbix/api_jsonrpc.php"
self.header = {"Content-Type": "application/json"}
self.authID = self.user_login()
def user_login(self):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "Admin",
"password": "zabbix"
},
"id": 0
})
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
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()
authID = response['result']
return authID
def get_data(self,data,hostip=""):
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
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
return 0
else:
response = json.loads(result.read())
result.close()
return response
def host_get(self,hostip):
#hostip = raw_input("