python3 zabbix3.4 API
Posted 运维百科
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 zabbix3.4 API相关的知识,希望对你有一定的参考价值。
这里使用python3,zabbix3.4 创建主机组-主机-应用集-监控项-触发器整个流程,脚本如下:
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
import requests
import json
import re
import subprocess
url = 'http://1.1.1.1/zabbix/api_jsonrpc.php'
username = 'admin'
password = '1111111111'
# 定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数
def requestJson(url, values):
data = json.dumps(values)
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=data, headers=headers)
output = json.loads(response.text)
try:
message = output['result']
except:
message = output['error']['data']
print(message)
quit()
return output['result']
# 2、API接口认证的函数,登录成功会返回一个Token
def authenticate(url, username, password):
values = {'jsonrpc': '2.0',
'method': 'user.login',
'params': {
'user': username,
'password': password
},
'id': '0'
}
idvalue = requestJson(url, values)
return idvalue # 结果是一个token值:cc75ed2a314906a835ac0786266468ac
# 创建主机组:
def creategroup(auth, group_name):
values = {
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": group_name
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output
# 根据组名获取组id: 获取"wangjie_test" 组的id
def get_group(auth, group_name):
values = {
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": { # 如果没有filter 默认会获取所有组信息
"name": [
group_name,
]
}
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output[0]['groupid']
# 创建主机,并添加到对应主机组中
def create_host(auth, hostname, ip, gid, templateid):
values = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
# 1、主机名称
"host": hostname,
# 2、为主机创建的接口
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": "10050"
}
],
# 3、将主机添加到主机组中
"groups": [
{
"groupid": gid,
}
],
# 4、链接一个模板
"templates": [
{
"templateid": templateid
}
],
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output
# 获取主机组 id
def get_group(auth, group_name):
values = {
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": { # 如果没有filter 默认会获取所有组信息
"name": [
group_name,
]
}
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output[0]['groupid']
# 获取模板id:根据模板名称获取模板id
def get_template(auth, template_name):
values = {
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": ["host", "templateid"],
"filter": {
"host": [template_name, ]
}
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output[0]['templateid']
# 模板添加到指定的主机中
def massadd_template_hosts(auth, templateid, hostid):
values = {
"jsonrpc": "2.0",
"method": "template.massadd",
"params": {
"templates": [
{
"templateid": templateid
},
],
"hosts": [
{
"hostid": hostid
}
]
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output
# 创建应用集
def create_application(auth, app_name, hostid):
values = {
"jsonrpc": "2.0",
"method": "application.create",
"params": {
"name": app_name,
"hostid": hostid
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output # 运行后就可以在对应主机的监控项页面看到刚创建的监控项了
# 根据主机和应用集的名称获取应用集的id
def get_application(auth, hostid, name):
values = {
"jsonrpc": "2.0",
"method": "application.get",
"params": {
"output": "extend",
"hostids": hostid,
"sortfield": "name",
"filter": {
"name": [name, ]
}
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output[0]["applicationid"] # 运行后就可以在对应主机的监控项页面看到刚创建的监控项了
# 创建监控项
def create_item(auth, item_name, item_key, hostid, interfaceid, applications_id):
values = {
"jsonrpc": "2.0",
"method": "item.create",
"params": {
"name": item_name,
"key_": item_key, # 键值必须和agent的key值相同
"hostid": hostid,
"type": 7,
"value_type": 2,
"interfaceid": interfaceid,
"applications": [applications_id], # 监控项可以归属默写 "应用集" 这里就不关联了
"delay": "30s",
"history": "3d"
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
return output
# 获取主机id 和 interfaceid
def get_host(auth, hostname):
values = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ['name', 'hostid', ],
"filter": {
"host": [hostname, ]
},
"selectInterfaces": [ # 添加这个参数为了获取interfaceid的值
"interfaceid",
"ip"
],
},
"auth": auth,
"id": 1
}
output = requestJson(url, values)
interfaceid = output[0]['interfaces'][0]['interfaceid']
hostid = output[0]['hostid']
return {'interfaceid': interfaceid, 'hostid': hostid}
# 创建 一个/多个 触发器
def create_trigger(auth, description, expression, type):
values = {
"jsonrpc": "2.0",
"method": "trigger.create",
"params": [
{
"description": description, # 名称:告警描述信息
"expression": expression, # 表达式
"priority": "4", # 设置告警级别(0:未分类; 1:信息; 2:警告; 3:一般严重 ...)
"type": type # 事件生产模式,端口监控是0,日志是1
},
# { # 创建多个只需加一个字典即可
# "description": "Too many processes on {HOST.NAME}",
# "expression": "{Linux server:proc.num[].avg(5m)}>300",
# }
],
"auth": auth,
"id": 4
}
output = requestJson(url, values)
return output # 运行后就可以在对应主机的监控项页面看到刚创建的监控项了
def get_tomcat_name():
tomcat_name = "/bin/find /usr/local/installed -name 'server.xml' | sort -n | uniq -c | awk -F'/' '{print $5}'"
t = subprocess.Popen(tomcat_name, shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf8')
tomcats = []
for tomcat in t.split('\n'):
if len(tomcat) != 0:
tomcats.append(tomcat)
return tomcats
host_group = "wangjie_test2" # 主机组名称
template_name = "Template OS Linux" # 模板名称
host_name = "1.1.1.5" # 主机名称
host_ip = "1.1.1.5" # 主机ip
app_name = ["Logs", "Monitor_Port"] # 应用集名称列表
tomcat_list = get_tomcat_name()
description_log = []
description_port = []
expression_log = []
expression_port = []
trigger_expression_log = []
trigger_expression_port = []
auth = authenticate(url, username, password) # 登录获取token
try:
gid = get_group(auth, host_group) # 获取主机组id
except IndexError as e:
creategroup(auth, host_group)
gid = get_group(auth, host_group) # 获取主机组id
print("主机组id", gid)
template_id = get_template(auth, template_name)
print("模板id", template_id)
# #创建主机
create_host(auth, host_name, host_ip, gid, template_id)
host_dic = get_host(auth, host_name)
host_id = host_dic['hostid']
print(host_id)
# 创建应用集
for name in app_name:
print(name)
create_application(auth, name, host_id)
# 给对应的应用集创建监控项
for tomcat in tomcat_list:
tomcat_port = re.split('-', tomcat)[-1]
print(tomcat_port)
description_log.append(tomcat + "日志监控")
description_port.append(tomcat + "端口监控")
tomcat_log_dir = "/usr/local/installed/" + tomcat + "/logs/system_sys.log"
trigger_expression_log.append("{%s:log[%s,ERROR].regexp(ERROR)}=1 and {%s:log[%s,ERROR].count(300,ERROR)}<6" % (
host_ip, tomcat_log_dir, host_ip, tomcat_log_dir))
trigger_expression_port.append("{%s:net.tcp.port[%s,%s].last()}<>1" % (host_ip, host_ip, tomcat_port))
expression_log.append("log[%s,ERROR]" % tomcat_log_dir)
expression_port.append("net.tcp.port[%s,%s]" % (host_ip, tomcat_port))
for name in app_name:
applications_id = (get_application(auth, host_id, name))
if name == "Logs":
for i in range(len(description_log)):
create_item(auth, description_log[i],
expression_log[i],
host_dic['hostid'], host_dic['interfaceid'], applications_id)
if name == "Monitor_Port":
for i in range(len(description_port)):
create_item(auth, description_port[i],
expression_port[i],
host_dic['hostid'], host_dic['interfaceid'], applications_id)
###为了监控项创建触发器
for i in range(len(tomcat_list)):
create_trigger(auth, description_log[i], trigger_expression_log[i], 1)
create_trigger(auth, description_port[i], trigger_expression_port[i], 0)
以上是关于python3 zabbix3.4 API的主要内容,如果未能解决你的问题,请参考以下文章