创建web监控
#! /usr/bin/env python3
import os
import json
import requests
from GetZabbixToken import GetToken, headers, urls, hostname
def OpenFile():
createList = []
FileLocal = os.path.join(os.path.dirname(__file__), 'zabbix.txt')
with open(FileLocal, mode='r', encoding='utf-8') as zabbix:
txt = zabbix.read()
data = txt.rstrip().split('\n')
for item in data:
item2 = item.split('----')
name = item2[0]
hostid = item2[1]
appid = item2[2]
value = item2[3]
tupleList = (name, hostid, appid, value)
createList.append(tupleList)
return createList
# 创建web监控
def CreateWebCheck(*args):
for value in args:
payload = {
"jsonrpc": "2.0",
"method": "httptest.create",
"params": {
"name": value[0],
"hostid": value[1],
"applicationid": value[2],
"steps": [
{
"name": value[0],
"url": value[3],
"status_codes": "200",
"no": 1
}
]
},
"id": 1,
"auth": GetToken()
}
response = requests.request("POST", urls, json=payload, headers=headers)
print(response.text)
# 创建触发器
def CreateTriggerPort(*args):
for value in args:
payload = {
"jsonrpc": "2.0",
"method": "trigger.create",
"params": [
{
# 触发器描述
"description": f"访问{value[0]}接口错误!!",
# 报警触发器表达式
"expression": "{%s:web.test.rspcode[%s,%s].last(,5)}<>200" % (hostname, value[0], value[0]),
"url": value[2],
"priority": 5,
"comments": f"访问{value[0]}接口错误!! \n访问地址:{value[2]}",
# 启用恢复表达式
"recovery_mode": 1,
# 恢复触发器表达式
"recovery_expression": "{%s:web.test.rspcode[%s,%s].last(,5)}=200" % (hostname, value[0], value[0])
}
],
"id": 1,
"auth": GetToken()
}
response = requests.request("POST", urls, json=payload, headers=headers)
print(json.loads(response.text))
def main():
tupleList = OpenFile()
for value in tupleList:
try:
CreateWebCheck(value)
CreateTriggerPort(value)
except Exception as e:
print(f"Error {e}")
if __name__ == "__main__":
main()
可以看到我们从其他Python文件中引了一些东西,GetZabbixToken.py 文件就直接放在下面做参考了
GetZabbixToken.py
#! /usr/bin/env python3
import json
import requests
urls = 'http://192.168.1.110/zabbix/api_jsonrpc.php'
user = "Admin"
password = "zabbix"
hostname = "Zabbix server"
parms = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": user,
"password": password
},
"id": 1
}
headers = {
"Content-Type": "application/jsonrequest",
"content-type": "application/json"
}
def GetToken():
"""使用python的requests模块调用zabbix API接口"""
req = requests.get(urls, headers=headers, data=json.dumps(parms))
key = req.text
dic = json.loads(key)
token = dic['result']
# print("Zabbix api token of %s is: " % (user), token)
return token
if __name__ == '__main__':
GetToken()
zabbix.txt
# 简单的一个示范
百度----你的主机id----0(应用集id,没有默认为0)----https://www.baidu.com
获取web监控列表
有时想迁移zabbix莫个主机的web监控,看它太多有嫌麻烦不想一个一个的复制迁移的话,直接用脚本将它已有的web监控写入文本,在用脚本添加到主机里面就好了
#! /usr/bin/env python3
import requests
from GetZabbixToken import GetToken, headers, urls
def GetWebCheck(host_id):
""""""
payload = {
"jsonrpc": "2.0",
"method": "httptest.get",
"params": {
"output": "extend",
"selectSteps": "extend",
"hostids": host_id
},
"auth": GetToken(),
"id": 1
}
response = requests.request("POST", urls, json=payload, headers=headers)
# 获取为dict类型
rjson = response.json()
rlist = rjson["result"]
# 是个list包含多个web监控dict
for dictvalue in rlist:
name = dictvalue["name"]
hostid = dictvalue["hostid"]
checkurl = dictvalue["steps"][0]["url"]
# 拼接为文本
text = f'{name}----{hostid}----{checkurl}'
# 追加写入指定文件
with open('./zabbix.txt', 'a+', encoding='utf-8') as f:
f.writelines(text + '\n')
if __name__ == '__main__':
host_id = '主机id'
GetWebCheck(host_id)
可以看到我脚本中好像没获取web监控的应用集id唉。其实每个主机的应用集是不同用的,要在主机里面单独创建应用集后,才能获取该应用集在这个主机中的应用集id。
具体可以查看官网文档: https://www.zabbix.com/documentation/5.0/zh/manual/api/reference/httptest/create