zabbix API创建监控项、模板

一、zabbix API简介

zabbix开放了一套完善的API,可用于二次开发、API自动化操作等,zabbix API是基于json-rpc2.0协议的web API,即客户端对API的请求和响应使用json格式编码。Zabbix API由许多名义上分组的独立API方法组成。大多数API至少包含四种方法: getcreateupdatedelete

zabbix5.0手册现已支持中文,官方手册地址:zabbix 官方中文手册


二、pyzabbix 简介

pyzabbix是用python封装的zabbix api,支持1.8至5.0 API使用。github地址:pyzabbix

安装pyzabbix

pip install pyzabbix

测试API

from pyzabbix import ZabbixAPI

zapi = ZabbixAPI("http://192.168.43.130/zabbix") #zabbix地址
zapi.login("Admin", "zabbix")  #zabbix用户名、密码
print("Connected to Zabbix API Version %s" % zapi.api_version())

for h in zapi.host.get(output="extend"):
    print(h['hostid'])

输出如下,正常连接至zabbix

Connected to Zabbix API Version 4.0.16
10340
10366
10267
10333
10334
10335
10337
10355
10358

三、通过API创建监控项、触发器和模板

1.创建模板

在zabbix中模板必须有所属模板组,所以创新之前需要获取模板组id

def get_template_group_id(api, name):  #入参 api对象、组名称
    group_re = api.hostgroup.get(output=['groupid'], filter={"name": [name]})
    if group_re:
        group_id = group_re[0]['groupid']
    else:
        group_id = ''
    return group_id

def create_template(api, gid, name, alias): #入参 api对象、模板所属组id、名称(只能英文)、别名
    ret = api.template.create(
        host=name,
        name=alias,
        groups={
            'groupid': gid
        }
    )
    print("template_name:{}".format(name))
    return ret['templateids'][0]

2.为模板创建监控项、触发器

def create_item_trigger(api, template_id, template_name, ip_addr,port, status=1, delay='1m', expression='=0', level=3, atime=3):

    item_name = 'Telnet{0} 端口(10050)状态'.format(ip_addr)   #监控项名称
    key = 'net.tcp.port[{0},10050]'.format(ip_addr)  #键值 
    item_id = api.item.create(
        name=item_name,
        key_=key,
        hostid=str(template_id),
        type=7,
        value_type=3,
        delay=delay
    )['itemids'][0]
    print("{} created success!".format(ip_addr))
    trigger_id = api.trigger.create(
        description="端口({0})状态异常".format(port),  #触发器名称
        expression='{%s:%s.min(#%d)}%s' % (template_name, key, atime, expression),  #触发器表达式
        priority=level,
        status=status
    )['triggerids'][0]
    print("item_id:{}\n trigger_id:{}\n".format(item_id,trigger_id))

四、创建一个完整模板

以模板名称为API_create_template ,监控项为Telnet192.168.43.140 端口(10050)状态 ,触发器为 端口(10050)状态异常为例创建监控模板。

from pyzabbix import ZabbixAPI, ZabbixAPIException

def get_api(url, user, pw):
    api = ZabbixAPI(url)  # api地址
    api.login(user, pw)  # Zabbix用户名、密码
    return api

def get_template_group_id(api, name):
    group_re = api.hostgroup.get(output=['groupid'], filter={"name": [name]})
    if group_re:
        group_id = group_re[0]['groupid']
    else:
        group_id = ''
    return group_id

def read_file(fn):
    data = get_data(fn)
    return data

def create_template(api, gid, name, alias):
    ret = api.template.create(
        host=name,
        name=alias,
        groups={
            'groupid': gid
        }
    )
    print("template_name:{}".format(name))
    return ret['templateids'][0]

def get_template_id(api,tpl_name):
    tpl_id = ''
    try:
        res = api.template.get(filter={'host':tpl_name}, output=['templateid'])
        if res:
            tpl_id = res[0]['templateid']

    except ZabbixAPIException as e:
            print(e)
    return tpl_id


def create_item_trigger(api, template_id, template_name, ip_addr,port, status=1, delay='1m', expression='=0', level=3, atime=3):

    item_name = 'Telnet{0} 端口(10050)状态'.format(ip_addr)   #监控项名称
    key = 'net.tcp.port[{0},10050]'.format(ip_addr)  #键值 
    item_id = api.item.create(
        name=item_name,
        key_=key,
        hostid=str(template_id),
        type=7,
        value_type=3,
        delay=delay
    )['itemids'][0]
    print("{} created success!".format(ip_addr))
    trigger_id = api.trigger.create(
        description="端口({0})状态异常".format(port),  #触发器名称
        expression='{%s:%s.min(#%d)}%s' % (template_name, key, atime, expression),  #触发器表达式
        priority=level,
        status=status
    )['triggerids'][0]
    print("item_id:{}\n trigger_id:{}\n".format(item_id,trigger_id))

if __name__ == '__main__':
    template_name=template_alias="API_create_template"
    api=get_api("http://192.168.43.130/zabbix","Admin","zabbix")  #创建api对象
    gid=get_template_group_id(api, 'Templates/Applications') #获取模板分组id
    tpl_id=create_template(api, gid, template_name, template_alias) #创建模板
    tpl_id=get_template_id(api,template_name)           
    try:
        create_item_trigger(api,tpl_id,template_name,"192.168.43.40",10050) #创建监控项、触发器 
    except Exception as e:
        print(e)
    

结果如下:

image-20210430152601148

包含一个监控项和触发器

image-20210430152708053


有不理解的地方可在评论区指出。欢迎收藏、点赞、提问。关注顶级饮水机管理员,除了管烧热水,有时还做点别的。

posted @ 2021-04-30 15:34  justtest1  阅读(770)  评论(0编辑  收藏  举报