zabbix库连接信息,文件名为Conn.py
import pymysql
"""
获取后台数据库连接
"""
def CON():
con = pymysql.connect(host='rm-xxx.xxxxx.rds.aliyuncs.com', user='xxx',
password='xxxx', db='zabbix')
return con
多台机器信息获取通过向项目目录下一个hosts.list文件里填入,内容格式如下:
slsk_aliyun_bili_501_BT_2|ip地址|10050|slsk|linux
slsk_aliyun_bili_501_GW-LG_2|ip地址|10050|slsk|linux
....
以|分割,第一列是机器主机名,第二列是机器ip地址,第三列是zabbix_agent传输端口,第四列是zabbix机器组名字,第五列表示是什么系统,目前只支持linux
zabbix api class封装,文件名为utils.py,
import json
import requests
from . import Conn
from config import basedir
import os
from action.actlog import HaLog
class ZabbixApi:
def __init__(self): # 初始化信息
self.url = 'http://zabbix访问地址/api_jsonrpc.php'
self.user = 'zabbix账号'
self.passwd = 'zabbix密码'
self.header = {"Content-Type": "application/json-rpc"}
self.HostIP = [] # ip存放列表
self.HostName = [] # 主机名存放列表
self.HostTemplate = [] # 模板名称存放列表
self.HostGroup = [] # 主机组存放列表
self.l = HaLog("zabbix.log", "info", log_path="/home/hero/log")
def UserLogin(self):
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.passwd
},
"id": "1"
}
return self.UrlRequest(data)
def UrlRequest(self, data):
request = requests.post(self.url, json.dumps(data), headers=self.header)
response = json.loads(request.text)
self.l.info(str(response))
return response
def HostInFo(self): # 将文件主机信息分类加入每个列表中
host_info_path = os.path.join(basedir, "hosts.list")
with open(host_info_path, encoding='utf-8', mode='r') as f:
qsq = f.readlines()
for list in qsq:
host_name = list.strip().split('|')[0]
self.HostName.append(host_name)
host_ip = list.strip().split('|')[1]
self.HostIP.append(host_ip)
# host_port = list.strip().split('|')[2]
host_group_name = list.strip().split('|')[3]
self.HostGroup.append(host_group_name)
template_name = list.strip().split('|')[4]
self.HostTemplate.append(template_name)
print(self.HostName, self.HostIP, self.HostGroup, self.HostTemplate)
f.close()
return self.HostName, self.HostIP, self.HostGroup, self.HostTemplate
def HostInFoFromlist(self, info_list):
"""
将列表转换为zabbix参数
例:
["slsk_aliyun_bili_501_BT_2|ip地址|10050|slsk|linux",
"slsk_aliyun_bili_501_GW-LG_2|ip地址|10050|slsk|linux",
...]
迭代循环列表中内容,将字符串按照| 分隔,重新分解为zabbix 主机信息。
:param info_list:
:return:
"""
for info in info_list:
host_name = info.strip().split('|')[0]
self.HostName.append(host_name)
host_ip = info.strip().split('|')[1]
self.HostIP.append(host_ip)
# host_port = list.strip().split('|')[2]
host_group_name = info.strip().split('|')[3]
self.HostGroup.append(host_group_name)
template_name = info.strip().split('|')[4]
self.HostTemplate.append(template_name)
return self.HostName, self.HostIP, self.HostGroup, self.HostTemplate
def CreateHost(self, HostName, HostIP, HostGroup, HostTemplate, new_auth): # 创建主机
for i in range(len(HostIP)):
ip = HostIP[i]
name = HostName[i]
temp = HostTemplate[i]
# 暂时只给支持linux机器的创建
if temp == 'linux':
tempid = 10001
elif temp == 'windows':
tempid = 0000
else:
tempid = 0000
group = HostGroup[i] # 根据group名获取到groupid
# if group == 'qiuqiu_prod':
# groupid = 21
if group:
con = Conn.CON()
sql = "SELECT groupid FROM hstgrp where name='%s';" % group
CURSOR = con.cursor()
CURSOR.execute(sql)
try:
groupid = CURSOR.fetchone()[0]
except:
groupid = None
finally:
CURSOR.close()
con.close()
else:
self.l.write("group 为空")
return {"success": False, "msg": "group 为空"}
if groupid is None:
self.l.write("未获取到groupid")
return {"success": False, "msg": "未获取到groupid"}
data = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": name,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": "10050"
}
],
"groups": [
{
"groupid": groupid
}
],
"templates": [
{
"templateid": tempid
}
],
},
"auth": new_auth,
"id": 1
}
res = self.UrlRequest(data)
try:
if res['error']:
return {"success": False, "msg": res['error']['data']}
except:
pass
if i == len(HostIP) - 1:
return {"success": True, "msg": "所有主机已创建完成!"}
def Host_Get(self, new_auth, hostName):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {
"host": hostName
}
},
"auth": new_auth,
"id": 1
}
response = self.UrlRequest(data)
self.l.write(response)
if not len(response['result']):
self.l.write("\033[041m %s \033[0m is not exist" % hostName)
return False
self.l.write("主机数量: \033[31m%s\033[0m" % (len(response['result'])))
for host in response['result']:
# print host
if len(hostName) == 0:
return False
else:
return host['hostid']
def DeleteHost(self, HostName, HostIP, HostGroup, HostTemplate, new_auth): # 删除主机
hostid_list = []
for i in range(len(HostIP)):
name = HostName[i]
hostid = self.Host_Get(new_auth, name)
if not hostid:
return {"success": False, "msg": "主机 %s 删除失败 !" % name}
hostid_list.append(hostid)
data = {
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": new_auth,
"id": 1
}
self.UrlRequest(data)
return {"success": True, "msg": "'所有主机已删除完成!"}
router函数,这里通过flask编写
from . import zabbix
from flask import make_response
from router_zabbix.utils import ZabbixApi
@zabbix.route('/create_hosts')
def create_hosts():
result_dict = {}
try:
res = ZabbixApi().UserLogin()
auth = res['result']
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
return make_response(result_dict, 222)
try:
HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFo()
info = ZabbixApi().CreateHost(HostName, HostIP, HostGroup, HostTemplate, auth)
if not info["success"]:
result_dict["success"] = False
result_dict["msg"] = info["msg"]
return make_response(result_dict, 222)
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
return make_response(result_dict, 222)
result_dict["success"] = True
result_dict["msg"] = info["msg"]
return make_response(result_dict, 200)
@zabbix.route('/delete_hosts')
def delete_hosts():
result_dict = {}
try:
res = ZabbixApi().UserLogin()
auth = res['result']
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
return make_response(result_dict, 222)
try:
HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFo()
info = ZabbixApi().DeleteHost(HostName, HostIP, HostGroup, HostTemplate, auth)
if not info["success"]:
result_dict["success"] = False
result_dict["msg"] = info["msg"]
return make_response(result_dict, 222)
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
return make_response(result_dict, 222)
result_dict["success"] = True
result_dict["msg"] = info["msg"]
return make_response(result_dict, 200)
def delete_hosts_cmd(info_list):
"""
命令行方式调用zabbix api 用于删除 主机信息
:return:
"""
result_dict = {}
try:
res = ZabbixApi().UserLogin()
auth = res['result']
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
print('Zabbix 认证失败:')
print(result_dict)
return {"success": False, "msg": 'Zabbix 认证失败:{}'.format(result_dict)}
try:
HostName, HostIP, HostGroup, HostTemplate = ZabbixApi().HostInFoFromlist(info_list)
info = ZabbixApi().DeleteHost(HostName, HostIP, HostGroup, HostTemplate, auth)
if not info["success"]:
result_dict["success"] = False
result_dict["msg"] = info["msg"]
print("Zabbix 删除失败:")
print(result_dict)
return {"success": False, "msg": 'Zabbix 删除失败:{}'.format(result_dict)}
except Exception as E:
result_dict["success"] = False
result_dict["msg"] = E
print(result_dict)
return {"success": False, "msg": 'Zabbix 操作失败:{}'.format(result_dict)}
result_dict["success"] = True
result_dict["msg"] = info["msg"]
print(result_dict)
return {"success": True, "msg": result_dict}