問題:zabbix上突然發(fā)現有臺服務器的item監(jiān)控項通過自動發(fā)現規(guī)則創(chuàng)建了5w多個監(jiān)控項。
解決思路
1.在web界面將host刪除,結果無法刪除,點擊刪除后無反應
2.在web界面先將模板取消并清理,結果發(fā)現取消后,item還是存在,無法刪除。
3.通過腳本使用api刪除host,結果發(fā)現請求超時,無法從api將主機刪除。
4.通過數據庫直接將host刪除,但是考慮到數據庫會繼續(xù)保存5w個item,強迫癥患者堅決不允許。
于是懷疑是不是由于item有5w多個,倒是zabbix數據庫里面無法處理過來。
然后產生如下思路:
1.通過web界面每次刪除1000個,手動刪除。--自動化運維表示這么做太low
2.通過api接口刪除特定主機item,這個可以有,開干!!!
Python腳本
思路為,獲取hostid,根據hostid獲取所有的itemid,然后調取api刪除所有itemid
網上看了很多資料,全部都是如何創(chuàng)建item的,沒有批量刪除的,于是自己寫一個
環(huán)境:能聯通zabbix_server的主機,python3環(huán)境
執(zhí)行命令pip install zabbix_api
腳本如下:
#-*- coding:utf8 -*-
import json,sys,argparse
from zabbix_api import ZabbixAPI
server = "http://xxx.xxx.xxx.xxx/zabbix"
username = "Admin"
password = "zabbix"
zapi = ZabbixAPI(server=server, path="", log_level=0)
zapi.login(username, password)
#解析參數
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="host name")
args = parser.parse_args()
if not args.host:
args.host = raw_input('host: ')
return args
#根據hostname查詢hostid
def get_host_id(host):
get_host_id = zapi.host.get(
{
"output": "hostid",
"filter": {
"host":host.split(",")
}
}
)
host_id = []
host_id.append([I['hostid'] for I in get_host_id])
return host_id[0]
#查詢host中所有item存入item_id列表中
def get_host_item(hosts_id):
get_item_id = zapi.item.get(
{
"output": ["itemid","key_"],
"hostids": hosts_id,
# "filter": {
# "host":host.split(",")
}
)
item_id = []
item_id.append([I['itemid'] for I in get_item_id])
return item_id[0]
#刪除host
def delete_host(hosts_id):
hosts_delete = zapi.host.delete(hosts_id)
return "host delete success!"
#刪除host中item
def delete_host_item(itemid):
hosts_delete = zapi.item.delete(itemid)
return "host_item "+itemid[0]+" delete success!"
if __name__ == "__main__":
args = get_args()
host_id = get_host_id(args.host)
item_id = get_host_item(host_id)
#此處的for循環(huán)是將列表中所有元素全部單個定義為新的列表,然后調取api刪除,因為一次5w個item的列表,api請求會超時。
for i in range(len(item_id)):
itemid = []
itemid.append(item_id[i])
print(delete_host_item(itemid))
print(delete_host(hosts_id))
重要?。?!首先在web界面將template去掉,unlink即可。
執(zhí)行方式:python zabbix_del.py --host='test_host' &
放在后臺自己執(zhí)行了一個小時刪除完了。
參考文章:https://www.zabbix.com/documentation/3.4/zh/manual/api/reference/item/delete