场景
我们日常在管理Zabbix 的时候,经常会需要批量添加模板和批量删除模板,Zabbix页面是提供的批量链接的功能,但是它链接的也只是当前页的主机,我们想扩展这个功能,在链接的时候,可以批量链接整个主机群组,也可以指定链接某台主机,也可以指定链接包含某个字符的多个主机。
提供的功能
查询模板id
select_template(self, template_name)
查询主机群组id
select_group(self, group_name)
查询指定主机id
select_host(self, hostname=‘‘, groupid=‘‘):
-
当需要查询所有的主机id时
online_zabbix.select_host()
-
当需要查询指定主机名称id时
online_zabbix.select_host(name)
-
当需要查询指定主机群组的指定主机名称id时
online_zabbix.select_host(name,groupid)
hostslist = online_zabbix.select_host(‘biz‘) print(hostslist)
主机链接模板
hosts_add_template(self, template_name, hostname, group_name=‘‘)
- 当我们想所有的主机链接某个模板,写法 为
online_zabbix.hosts_add_template(‘Linux‘, ‘‘)
- 当我们想包含 特定的主机名或者特定的主机关键字的主机链接某个模板 写法为:
online_zabbix.hosts_add_template(‘Linux‘, ‘biz‘)
- 当我们想特定的主机群组 包含 特定的主机名或者特定的主机关键字的主机链接某个模板 写法为:
online_zabbix.hosts_add_template(‘Linux‘, ‘biz‘,‘test‘)
示例:
online_zabbix.hosts_add_template(‘Linux‘, ‘biz‘,‘ test‘)
主机删除模板
用法同上
hosts_delete_template(self, template_name, hostname, group_name=‘‘)
online_zabbix.hosts_delete_template(‘Linux‘, ‘biz‘, ‘test‘)
查询指定业务的接入心跳服务(特定场景无需关注)
online_zabbix.statistics_service(‘djx‘, ‘Heart Monitor‘,)
查询所有业务接入心跳服务(特定场景无需关注)
online_zabbix.statistics_total()
脚本
基于python3 , 需要安装 requests 模块
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/7/1 15:04
# @Author : dongjiaxiao
# @Email :
# @File : hosts_template.py
# @Desc :
import requests
import json
class ZabbixApi:
def __init__(self, url,username,password):
self.url = url
self.headers = {
‘User-Agent‘: ‘python/3.6‘,
‘Content-Type‘: ‘application/json‘
}
self.authdata = {
"jsonrpc": "2.0",
"method": "user.login",
"params":
{"user": username, "password": password},
"id": 1666,
}
self.token = self.get_token()
def post_request(self, data):
"""
发起请求和获取响应内容
:param data: body 数据
:return:
"""
result = {‘code‘: 0, ‘data‘: ‘‘, ‘msg‘: ‘‘}
postdata = json.dumps(data)
try:
response = requests.post(self.url, headers=self.headers, data=postdata, timeout=30)
if response.status_code == 200:
res = response.json()
if res.get(‘result‘) != None: # 当 [] 也表示执行成功
result[‘code‘] = 1
result[‘data‘] = res.get(‘result‘)
else:
result[‘msg‘] = res
else:
result[‘msg‘] = response.text + "status_code:" + str(response.status_code)
except Exception as e:
result[‘msg‘] = e
print("error{}".format(e))
return result
def get_token(self):
"""
获取Token
:return: token 值
"""
token = None
res = self.post_request(self.authdata)
if res.get(‘code‘) and res.get(‘data‘):
token = res.get(‘data‘)
else:
print(res.get(‘msg‘))
return token
def select_group(self, group_name):
"""
寻找主机群组id
:param groupname: 主机群组名
:return group_ids: 主机群组id 列表
"""
group_ids = []
post_data = {
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": ["hostid"],
"search": {
"name": group_name
}
},
"auth": self.token,
"id": 1666
}
group_data = self.post_request(post_data)
if group_data.get(‘code‘) and group_data.get(‘data‘):
for data in group_data.get(‘data‘):
group_ids.append(data.get(‘groupid‘))
return group_ids
def select_host(self, hostname=‘‘, groupid=‘‘):
"""
通过主机群组id或者主机名 查询主机id
:param hostname: 主机名
:param groupid: 主机群组id
:return: 主机列表
"""
host_info = None
if groupid: # 当不传入主机群组id 进入直接查询指定主机
post_data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid"],
"groupids": groupid,
"search": {
"name": hostname
}
},
"auth": self.token,
"id": 1666
}
else:
post_data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid"],
"search": {
"name": hostname
}
},
"auth": self.token,
"id": 1666
}
host_data = self.post_request(post_data)
if host_data.get(‘code‘) and host_data.get(‘data‘):
host_info = host_data[‘data‘]
return host_info
def select_template(self, template_name):
"""
通过模板名称获取模板id
:param template_name:
:return: 模板id信息
"""
template_info = None
post_data = {
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": ["templateid"],
"search": {
"name": template_name
}
},
"auth": self.token,
"id": 1666
}
template_data = self.post_request(post_data)
if template_data.get(‘code‘) and template_data.get(‘data‘):
template_info = template_data[‘data‘]
return template_info
def hosts_add_template(self, template_name, hostname, group_name=‘‘):
"""
主机群组的指定主机名 添加模板
:param group_name: 主机群组(支持不输入)
:param template_name: 模板名
:param hostname: 主机名(关键词)
:return:
"""
result = {‘code‘: 0, ‘msg‘: ‘‘}
if group_name:
hostlist = self.select_host(hostname, groupid=self.select_group(group_name))
else:
hostlist = self.select_host(hostname)
templatelist = self.select_template(template_name)
if hostlist and templatelist:
post_data = {
"jsonrpc": "2.0",
"method": "template.massadd",
"params": {
"templates": templatelist,
"hosts": hostlist,
},
"auth": self.token,
"id": 1666
}
add_data = self.post_request(post_data)
if add_data.get(‘code‘) and add_data.get(‘data‘).get(‘templateids‘) == templatelist:
result[‘code‘] = 1
else:
# 打印日志,添加失败
result[‘msg‘] = add_data
else:
result[‘msg‘] = "未找到主机/主机群组"
return result
def hosts_delete_template(self, template_name, hostname, group_name=‘‘):
"""
主机删除模板
:param template_name: 模板名称
:param hostname: 主机名(关键词)
:param group_name: 可选,指定主机群组
:return:
"""
result = {‘code‘: 0, ‘msg‘: ‘‘}
hostdata = self.select_host(hostname, groupid=self.select_group(group_name))
hostlist = list(map(lambda x: x[‘hostid‘], hostdata))
templatedata = self.select_template(template_name)
templatelist = list(map(lambda x: x[‘templateid‘], templatedata))
if hostlist and templatelist:
post_data = {
"jsonrpc": "2.0",
"method": "host.massremove",
"params": {
"templateids_clear": templatelist,
"hostids": hostlist,
},
"auth": self.token,
"id": 1666
}
add_data = self.post_request(post_data)
if add_data.get(‘code‘) and add_data.get(‘data‘).get(‘hostids‘) == hostlist:
result[‘code‘] = 1
else:
# 打印日志,添加失败
result[‘msg‘] = add_data
else:
result[‘msg‘] = "未找到主机/主机群组"
return result
def select_items(self, group_name, itemname, hostname=‘‘):
"""
查询指定主机和模板的监控项
:param group_name: 主机群组名称
:param itemname: 监控项关键词
:param hostname: 主机名称
:return:
"""
result = {‘code‘: 0, ‘data‘: ‘‘, ‘msg‘: ‘‘}
hostdata = self.select_host(hostname, groupid=self.select_group(group_name))
hostlist = list(map(lambda x: x[‘hostid‘], hostdata))
if hostlist :
post_data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["key_"],
"hostids": hostlist,
"search": {
"name": itemname
}
},
"auth": self.token,
"id": 1666
}
item_data = self.post_request(post_data)
if item_data.get(‘code‘) and item_data.get(‘data‘):
result[‘code‘] = 1
result[‘data‘] = list(map(lambda x: x[‘key_‘].split(‘[‘)[1].split(‘]‘)[0], item_data[‘data‘]))
else:
# 打印日志,添加失败
result[‘msg‘] = item_data
else:
result[‘msg‘] = "未找到主机/主机群组"
return result
def statistics_service(self, group_name, itemname, hostname=‘‘):
"""
统计心跳服务添加的应用和业务线
:param group_name: 主机群组
:param itemname: 对应的监控项
:param hostname: 对应的主机名/主机名关键字。
:return:
"""
res = self.select_items(group_name, itemname, hostname)
if res.get(‘code‘):
app_list = set(res.get(‘data‘)) # 列表转元组
service_list = set(map(lambda x: ‘-‘.join(x.replace(‘tomcat-‘, ‘‘).split(‘-‘)[0:-1]), app_list))
project_list = set(map(lambda x: x.split(‘-‘)[0], service_list))
print("{} 业务线添加了心跳检测: {} 应用:{}, {} 服务:{}".format(project_list, len(service_list), service_list,len(app_list), app_list))
else:
print(res.get(‘msg‘))
def statistics_total(self,projects):
"""
统计所有的心跳服务和应用和业务线
:return:
"""
projects = projects
itemname = ‘Heart Monitor‘
for project in projects:
self.statistics_service(project, itemname,)
online_zabbix = ZabbixApi(url=‘https://zabbix/api_jsonrpc.php‘,Admin,zabbix)