众所周知,zabbix是一款强大的分布式监控系统,集各家所长于一体,得到了广大SA的认可。其强大的管理界面也极其方便,但是美中不足的是,如果同时有大批量(50台+)的服务器需要添加监控时,这时,其图形界面反而显得有些臃肿了,好在zabbix 提供了一套强大的API管理接口,我们可以使用它快速地添加成千上万台服务器。
根据日常工作中常用到zabbix的功能,整理以下功能
1.基于zabbix 官方 api
2.提供查询单个或者多个host、hostgroup、template功能
3.提供增加host,hostgroup功能
4.提供disable host功能
5.增加删除host 功能
代码如下:
#!/usr/bin/python
#coding:utf-8
import json
import urllib2
from urllib2 import URLError
import sys,argparse
class zabbix_api:
def __init__(self):
self.url = 'http://localhost/api_jsonrpc.php' #修改URL
self.header = {"Content-Type":"application/json"}
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 " 33[041m 用户认证失败,请检查 ! 33[0m", e.code
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID
def host_get(self,hostName=''):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter":{"host":hostName}
},
"auth": self.user_login(),
"id": 1
})
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
else:
response = json.loads(result.read())
#print response
result.close()
print "主机数量: 33[31m%s 33[0m"%(len(response['result']))
for host in response['result']:
status={"0":"OK","1":"Disabled"}
available={"0":"Un