在工作中可能公司的服务器的数量过于庞大,当单次需要添加成百上千个被监控主机的时候,传统简单的zabbix的web端添加被监控主机工作量繁重,也容易出错。
那么这时候脚本自动化运行就显得尤为重要。今天就讲述一种利用ZABBIX-API接口进行批量增加被监控主机的操作。
1、编写ZABBIX-API-自定义库
自定义库不需要改动,不存在差异化,请注意使用python的版本,代码中有注明,请选择使用自己的版本
#!/usr/bin/python
# encoding: utf-8
#filename: zabbix_base_api.py
#author: LINFAN
#writetime:20190725
import json
import urllib.request #python3使用
#import urllib2 #python2使用
class zabbix_base_api(object):
def __init__(self,url = "http://192.168.73.9/api_jsonrpc.php" ,header = {"Content-Type": "application/json"}):
self.url = url
self.header = header
# post
def post_request(self,url, data, header):
# request = urllib2.Request(url, data, header) #python2使用
# result = urllib2.urlopen(request)
#
request = urllib.request.Request(url, data, header) #python3使用
result = urllib.request.urlopen(request)
# ccc = result.read()
# print (ccc)
# response = json.loads(ccc)
response = json.loads(result.read())
result.close()
return response
def json_data(self,method,params,authid):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": method,
"params": params,
"auth": authid,
"id": 1
})
request_info = self.post_request(self.url, data.encode('utf-8'), self.header)
return request_info
# 认证信息
def authid(self,user,password): #定json中auth的信息
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": user,
"password": password
},
"id": 1
})
authid = self.post_request(self.url, data.encode('utf-8'), self.header)
try:
return authid['result']
except KeyError:
print ('用户名或密码错误')
exit()
def text_process(self,file):
import re
find = re.compile(r"^#")
text_info = []
# f = open(file,"r",encoding='UTF-8')
f = open(file, "r")
text = f.readlines()
f.close()
for i in text:
if find.search(i.rstrip("\n")) == None:
text_info.append(i.rstrip("\n"))
return text_info
# 注销认证
def login_out(self,authid):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.logout",
"params": [],
"id": 1,
"auth": authid
})
a = self.post_request(self.url, data.encode('utf-8'), self.header)
return '认证信息已注销'
2.编写添加被监控主机的脚本
#!/usr/bin/python
# encoding: utf-8
import zabbix_base_api # 调用zabbix-API-自定义库
import time
z_api_con = zabbix_base_api.zabbix_base_api(url='http://SERVER_IP/api_jsonrpc.php')#填写自己的ZABBIX的服务端IP地址
def getHostid(method,ip,authid):
data = {
"output": ["hostid", "host"],
"filter": {
"ip": ip
},
"selectInterfaces": ["ip"],
"selectParentTemplates": ["name"]
}
responses = z_api_con.json_data(method, data, authid)
return responses
#请在web端将鼠标指向代理、组、模板的名称,就会出现对应的ID#
def hostCreate(method,ip,authid):
data = {
"host": ip,
"proxy_hostid": 13323, #代理唯一标识码
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": "10050" #端口
}
],
"groups": [
{
"groupid": 222 #组的唯一标识
}
],
"templates": [
{
"templateid": 14041 #模板的唯一标识
}
]
}
responses = z_api_con.json_data(method, data, authid)
return responses
def proxyGet(method,hostid,authid):
data = {
"output": "extend",
"selectInterface": "extend"
}
responses = z_api_con.json_data(method, data, authid)
return responses
def proxyUpdate(method,hostid,authid):
data = {
"proxyid": 10255, #此处不需要更改#
"hosts": [
hostid
]
}
responses = z_api_con.json_data(method, data, authid)
return responses
def main_all(authid):
file = open("a.txt", "r") #打开ip那个文件
lists = file.readlines()
print (lists)
add_file = open("c.txt","a+")
iplist = []
for list in lists:
ip = list.strip("\n")
#判断主机是否存在,存在将hostid和ip写入文件((c.txt)),不存在则创建,将IP写入文件(c.txt)
hostget = getHostid("host.get",ip,authid)["result"]
print(hostget)
if hostget:
hostid = hostget[0]["hostid"]
host = hostget[0]["host"]
add_file.writelines(hostid+"\t"+host+"\n")
else:
hostcreate = hostCreate("host.create",ip,authid)
print(hostcreate)
add_file.writelines(ip+"\n")
add_file.close()
file.close()
if __name__ == "__main__":
starttime = time.time()
print ("Process is running...")
authid = z_api_con.authid('zabbix的账户', 'zabbix的密码')
# authid = z_api_con.authid('admin','zabbix')
main_all(authid)
z_api_con.login_out(authid)
endtime = time.time()
print (endtime-starttime)
这里我是使用测试机在本地做了隧道,直接在本地利用pycha工具执行脚本。本人亲试,解放双手!哈哈