黄冈网站建设收费,网站建设费用说明,微信做自己的网站,网站建设公司普遍存在劣势调用zabbix api#xff0c;删除部分被监控主机。 简介代码部分配置文件config.jsonnamefile.txt 简介 当新主机上线时#xff0c;我们可以通过自动注册功能#xff0c;在zabbix中批量添加这些新主机。那当有主机需要下线时#xff0c;我们又该如何在zabbix中批量删除这些主… 调用zabbix api删除部分被监控主机。 简介代码部分配置文件config.jsonnamefile.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,headersheaders,datajson.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.loginparams {user: user,password: password,}self.auth self.send_request(method,params)# 退出登录def logout(self):method user.logoutparams []self.send_request(method,params)# 通过主机名获取主机idhost_lst为由主机名组成的列表输出由主机id组成的列表。def get_hostid_lst(self,hostname_file):method host.getparams {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.deleteparams self.hostid_lstself.send_request(method,params)def main():# 获得相关配置信息conf config.jsonconf_info get_conf_info(conf)url conf_info[api][url]user conf_info[api][user]password conf_info[api][password]# 获得待删除的主机名称hostname_file namefile.txthostname_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
[rootredis del_zbxhosts]# cat config.json
{api: {url: http://192.168.1.10/zabbix/api_jsonrpc.php,user: Admin,password: zabbix}
}namefile.txt
[rootredis del_zbxhosts]# cat namefile.txt
redis1
redis2
redis3