调用zabbix api,删除部分被监控主机。
- 简介
- 代码部分
- 配置文件
- config.json
- namefile.txt
简介
当新主机上线时,我们可以通过自动注册功能,在zabbix中批量添加这些新主机。那当有主机需要下线时,我们又该如何在zabbix中批量删除这些主机呢?我们可以使用python编写脚本, 通过调用zabbix api的方式,实现被监控主机的批量删除功能。这个脚本虽然简单,但同时涉及python和zabbix api的基础操作,很适合初学者将理论知识落地成为实践,通过理论实践相结合的方法,让我们能快速成长。
代码部分
# -*- coding: utf-8 -*-
import json
from urllib import request# 从配置文件中读取配置信息
def get_conf_info(conf):with open(conf) as f:conf_info = json.load(f)return conf_info# 从文件中读取主机名到列表中
def get_hostname_lst(hostname_file):with open(hostname_file) as f:ss = f.readlines()ss = [ i.strip() for i in ss ]return ss# 调用zabbix api
class call_zbxapi:def __init__(self,url):self.url = urlself.idx = 0self.auth = Noneself.hostid_lst = []# 发送request请求,执行相关指令def send_request(self,method,params):headers = {"Content-Type": "application/json-rpc"}data = {"jsonrpc": "2.0","method": method,"id": self.idx,"auth": self.auth,"params": params}req = request.Request(self.url,headers=headers,data=json.dumps(data).encode("UTF-8"))with request.urlopen(req) as res:res = res.read()ret = json.loads(res)if "result" in ret:result = ret["result"]return resultself.idx += 1 # 获取认证tokendef login(self,user,password):method = "user.login"params = {"user": user,"password": password,}self.auth = self.send_request(method,params)# 退出登录def logout(self):method = "user.logout"params = []self.send_request(method,params)# 通过主机名获取主机id,host_lst为由主机名组成的列表,输出由主机id组成的列表。def get_hostid_lst(self,hostname_file):method = "host.get"params = {"output": ["hostid"],"filter": {"host": hostname_file}}result = self.send_request(method,params)self.hostid_lst = [ i["hostid"].strip() for i in result ]# 删除hostid_lst中的主机def del_host(self):method = "host.delete"params = self.hostid_lstself.send_request(method,params)def main():# 获得相关配置信息conf = "config.json"conf_info = get_conf_info(conf)url = conf_info["api"]["url"]user = conf_info["api"]["user"]password = conf_info["api"]["password"]# 获得待删除的主机名称hostname_file = "namefile.txt"hostname_lst = get_hostname_lst(hostname_file)# 调用zbx api,通过主机名称获得主机id,再按照主机id删除主机zbxapi_caller = call_zbxapi(url)zbxapi_caller.login(user,password)zbxapi_caller.get_hostid_lst(hostname_lst)zbxapi_caller.del_host()zbxapi_caller.logout()if __name__ == "__main__":main()
配置文件
config.json
[root@redis del_zbxhosts]# cat config.json
{"api": {"url": "http://192.168.1.10/zabbix/api_jsonrpc.php","user": "Admin","password": "zabbix"}
}
namefile.txt
[root@redis del_zbxhosts]# cat namefile.txt
redis1
redis2
redis3