版权声明: https://blog.csdn.net/zhuangzi123456/article/details/83418992
使用说明:
1,该服务部署在zabbix server主机上,或者其他可以正常访问zbabix server的主机上,服务需要调用zabbix server的API;
2,代码基于flask,可以监听在指定的端口上等待调用接口,建议通过supervisor进行管理;
3,接口说明:
curl -L http://192.168.12.175:10052/regist/<hostCreate>/<visiblename>
参数:
(1)hostCreate:Zabbix server端添加新host的界面,输入的Host name值,该值必须与zabbix_agentd.conf文件中配置的Hostname一致;
(2)visiblename:Zabbix server端添加新host的界面,输入的Visible name值;
(3)传递的上述两个参数的值如果已经存在于zabbix server端,则会因为重复而无法成功添加主机;
#-*- coding: utf-8 -*-
from flask import Flask, request,json
import requests,time
zabbixurl = "http://127.0.0.1/api_jsonrpc.php"
config = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "2.2.3.1hh",
"name": "AAAAAAA-2.2.2.112hh",
"interfaces": [{
"type": 1,
"main": 1,
"useip": 1,
"ip": "ip",
"dns": "",
"port": "10050"
}],
"groups": [{
"groupid": "2"
}],
"templates": [{
"templateid": "10001"
},
{
"templateid": "10106"
},
{
"templateid": "10107"
}
]
},
"auth": "authID",
"id": 1
}
#获取登录authID,后续调用其他接口都要用到
def user_login():
zabbixurl = "http://127.0.0.1/api_jsonrpc.php"
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "autoregister",
"password": "XXXXXXXXXX"
},
"id": 0
}
headers = {
'Content-Type': 'application/json'
}
res = requests.post(zabbixurl, data=json.dumps(data), headers=headers)
return json.loads(res.text)['result']
#添加新host到zabbix server
def host_create(hostCreate,visiblename,authID):
config['auth'] = authID
config['params']['host'] = hostCreate
config['params']['name'] = visiblename
config['params']['interfaces'][0]['ip'] = str(request.remote_addr)
headers = {
'Content-Type': 'application/json'
}
res = requests.post(zabbixurl, data=json.dumps(config), headers=headers)
return res.text
#成功与否发送告警信息到钉钉群
def send_message(info):
headers = {
'Content-type':'application/json'
}
payload = {
'from':'devops.registToZabbix',
'system':'devops',
'message':info,
'level':'INFO',
'title':'New host regist to zabbix ',
'time':time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
}
res = requests.post("http://YOURHOST:PORT/api/send", data=json.dumps(payload),headers=headers)
#初始化Flask
app = Flask(__name__)
@app.route('/regist/<hostCreate>/<visiblename>')
def register(hostCreate,visiblename):
myAuthID = user_login()
result = host_create(hostCreate,visiblename,myAuthID)
resobj = json.loads(result)
try:
if 'result' in resobj.keys():
send_message('add host %s to zabbix success' %request.remote_addr)
return 'success'
else:
send_message('add host %s to zabbix failed' % request.remote_addr)
except Exception,e:
print e
send_message('add host %s to zabbix failed' % request.remote_addr)
return 'failed'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 10052)