Python调用Zabbix API接口批量修改(禁用/启用)触发器trigger
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python调用Zabbix API接口批量修改(禁用/启用)触发器trigger相关的知识,希望对你有一定的参考价值。
#!/bin/env python3
#coding:utf-8
import json
import os
import requests
url = "http://192.168.1.1/zabbix/api_jsonrpc.php" # 此处域名修改为相应的地址
headers = {
‘Content-Type‘: ‘application/json-rpc‘
}
def token_get(): #根据账号密码获取token
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "UserName", # zabbix管理员用户名
"password": "PASSWORD" # 账户密码
},
"auth": None,
"id": 1
}
json_data = json.dumps(data)
req = requests.post(url,data=json_data,headers=headers)
js_req = req.json()
return js_req[‘result‘]
def hosts_get(token): #获取所有主机信息
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output":["hostid","name"]
},
"auth": token,
"id": 1
}
json_data = json.dumps(data)
req = requests.post(url,data=json_data,headers=headers)
js_req = req.json()
return js_req[‘result‘]
def triggers_get(token,hostids):#通过指定的主机IDs获取所有相关Trigger信息
data = {
"jsonrpc": "2.0",
"method": "trigger.get",
"params": {
"output": "extend",
"hostids": hostids,
"search": {
"description": "Disk I/O" #修改此处更改触发器匹配字符串,我这边针对的是Disk I/O触发器进行处理
}
},
"auth": token,
"id": 1
}
json_data = json.dumps(data)
req = requests.post(url,data=json_data,headers=headers)
js_req = req.json()
return js_req[‘result‘]
def trigger_update(token,triggerid): #根据triggerid修改trigger状态:enable/disable
data = {
"jsonrpc": "2.0",
"method": "trigger.update",
"params": {
"triggerid": triggerid, #此处只能为单个id
"status": 1
},
"auth": token,
"id": 1
}
json_data = json.dumps(data)
req = requests.post(url,data=json_data,headers=headers)
js_req = req.json()
return js_req[‘result‘]
def pending():
path = ‘C:/Users/38997/Desktop/hostlist.txt‘ #需要处理的主机列表
f = open(path,‘r‘)
return f.read()
f.close()
if __name__==‘__main__‘:
trigger_count = 0
trigger_ids = []
hostids = []
token = token_get()
hostlist = hosts_get(token)
print(‘读取主机列表...‘)
unhosts = pending()
print("获取主机ID...")
for hostinfo in hostlist:
if hostinfo[‘name‘] in unhosts:
hostids.append(hostinfo[‘hostid‘])
print("主机IDs:",hostids,"
","获取所有触发器IDs...")
triggerlist = triggers_get(token,hostids)
for i in triggerlist:
trigger_count += 1
trigger_ids.append(i[‘triggerid‘])
print(trigger_ids,‘
共‘,trigger_count,‘条磁盘IO触发器‘)
select = input("开始处理 ‘y‘ or ‘n‘ ?
:")
if select == ‘y‘ or select == ‘‘:
for triggerid in trigger_ids:
print("开始禁用触发器:",triggerid,"
结果:",trigger_update(token,triggerid),"
","-"*30)
elif select == ‘n‘:
print("退出!")
exit()
else:
print("请输入:‘y‘ or ‘n‘!")
exit()
以上是关于Python调用Zabbix API接口批量修改(禁用/启用)触发器trigger的主要内容,如果未能解决你的问题,请参考以下文章
python3调用zabbix api接口对自动发现添加的主机修改主机名
利用python3 调用zabbix接口完成批量加聚合图形(screens)