zabbix: zabbix api包装的pyzabbix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34355232/article/details/83857114

pyzabbix是zabbixAPI的第三方python包装。那些个源码本身其实也是一个个单独操作的脚本,可以用命令行参数直接操作。pyzbx用了json来encode和decode请求数据和返回数据,并且用了urllib2中的一些方法来进行通讯

如果不是直接用它的脚本,而是自己定制相关程序的话基本上只用到ZabbixAPI这个类:
frompyzabbiximportZabbixAPI
zapi=ZabbixAPI(“server”)#server是指zabbixweb界面的url,比如http://192.168.1.101/zabbixzapi.login(“username”,“password”)#指的是zabbix系统里的用户名和密码,不是服务器本身的用户名和密码
之后就可以用zapi这个对象来实现程序和zabbixAPI之间的通讯了。

官方文档地址:http://www.zabbix.com/documentation/2.4/manual/api

zapi主要可以用的方法:

zapi.host.get , zapi.host.create , zapi.hostgroup.get , zapi.host.update , …等等。可以看到,这些方法和API的分类是一致的,这是写了这个pyzabbix模块的人包装得很巧妙的おかげ,用起来就方便很多了。 此外,这些方法大多都支持string/list的双重参数格式。意思就是说,当你想操作多次,但是又不想一条一条语句写的时候,可以直接传一个list进去,它会自动给你解析出来的。

■ 使用方法:

zapi.hostgroup.get(filter={‘groupid‘:‘xxx‘},output=[‘name‘,‘groupid‘],selectHosts=[‘name‘,‘hostid‘])
类似这样的语句。一个方法对应了官方API说明中的一种操作,这种对应关系很好懂,比如hostgroup.get就是获取主机组的信息,host.update就是更新主机的一些信息等等。至于每个方法的参数,就是和这个方法对应的那个API操作里规定的请求json串有关了。看几个请求串和方法参数的对应就会有感觉了= =。。字段是参数名,而字段值是参数值。

比如详细解释一下上面这条语句,它的意思就是

我要获取一些主机组的信息。

这个(些)主机组的groupid是xxx(filter的功能,如果不写filter,系统就默认把所有组的信息都返回给你了,当然通过指定groupid过滤出来的组肯定只有一个咯,但是返回来的json串仍然是个列表的形式,即使只有一项,这个后面还会说到)

我要得到的是这个(些)组的name和groupid字段(output的功能,output一定得是一个列表,可以是空,但是无论如何至少一定会返回groupid这个字段。如果写[‘extend‘]则是把所有字段的信息都返回)

用例:

#!/usr/bin/env python

from pyzabbix import ZabbixAPI
import json
import os,sys
import re,time
import logging
rule = json.load(file('D:\pycharm\project\REGION Manage Script\qn_rolerule.json'))    #template 文件

def login():
        zapi= ZabbixAPI("http://10.4.0.247")                                          #登录zabbix
        zapi.login("admin","zabbix")
        return zapi
        
def get_hostgroups(group_name):
        return zapi.hostgroup.get(search={"name":group_name },output="extend")        #搜索输入的组别,提取组id
        
def get_hosts(groupid):
        groupids = [groupid]
        return zapi.host.get(groupids=groupids,output="extend")                       #返回该组id 下的所有host 信息
        
def get_drules():
        return zapi.drule.get(output="extend")
        
def get_templates_by_names(template_names):
        return zapi.template.get(filter={"host": template_names})

def create_group(group_name):                                                         #创建组
    if not zapi.hostgroup.exists(name=group_name):
        zapi.hostgroup.create(name=group_name)

def create_host(group_name,host_name,ip):                                             #创建主机并附加指定模板
    groups=get_hostgroups(group_name)
    host_name=host_name.lower()
    ip_tail=ip.split(".")[-1]
    domain = "server-"+ ip_tail +".0." + host_name + ".ustack.in"
    for hostgroup in groups:
        groupid=hostgroup['groupid']
        ip_tail=ip.split(".")[-1]
        role = None
        for ru in rule:
            range = rule[ru]['range']
            if "-" in range:
                head = range.split("-")[0]
                tail = range.split("-")[1]
                if int(ip_tail) <= int(tail) and int(ip_tail) >=int(head):
                    role = ru
            else:
                if ip_tail == range:
                    role = ru
        template_names = rule[role]['templates']
        template_ids = get_templates_by_names(template_names)
        print domain,ip,groupid,template_ids
        zapi.host.create(host=domain,interfaces=[{
            "type":1,
            "main":1,
            "useip":1,
            "ip":ip,
            "dns":"",
            "port":'10050'
        }],groups=[{"groupid":groupid}],templates=template_ids)
        print  "Add Successfull!!!!!"
        #logging.info("%s,%s,%s,%s Add Successfull!!!!!"%(domain,ip,groupid,template_ids))

def create_macro(group_name,traffic,value):                                           #创建macro,不同主机有不同的macro
    groups=get_hostgroups(group_name)
    for group in groups:
        hosts=get_hosts(group['groupid'])
        for host in hosts:
            hostname=host["name"]
            hostid=host["hostid"]
            if not re.search("^server",hostname):continue
            m=re.search("[0-9]+",hostname).group()
            if m == "1":continue
            if m in ['64','65','66','67']:
                zapi.host.update(hostid=hostid,macros=[{"macro":"{$INP}","value":"35000"},
                                                  {"macro":"{$OUP}","value":"35000"},
                                                  {"macro":"{$INT}","value":"%s"%traffic},
                                                  {"macro":"{$OUT}","value":"%s"%traffic},
                                                  {"macro":"{$PDISK}","value":"%s"%value}])
            else:
                zapi.host.update(hostid=hostid,macros=[{"macro":"{$PDISK}","value":"%s"%value}])
            print hostname ,hostid,m,traffic,value
if __name__ == "__main__":
    zapi=login()
    region="qn"
    host_list=["31","32","35","36","39","40","44","45","46","47","48","49","50","53","54","61","62","63","64","65",
               "68","69","70","71","72","73","74","75","76","77","79","80","81","82","83","84","85","86","87","88","89","90","91"]       #添加主机,不建议用discovery
    ip_list=host_list
    if type(ip_list) == str:
        print "%s Must be a list,please checking !!!"%sys.argv[2]
        sys.exit()
    group_name="Region [%s 0]"% region.upper()
    if not zapi.hostgroup.exists(name=group_name):
       create_group(group_name)
    ip={"qn":"10.4.0."}
    if region in ip:
        for num in ip_list:
            value="20"
            traffic="300M"
            ipaddress=ip[region]+str(num)
            print group_name,region,ipaddress
            create_host(group_name,region,ipaddress)                                  #传参至函数
            time.sleep(5)
            create_macro(group_name,traffic,value)
    else:
        print "you input region error,please checking"

使用过程中的注意问题:
● 本身参数不存在,或者参数的值不合法的情况下(比如在上面那条语句中加个testpara="testvalue"之类的或者把output写成[‘name‘,‘groupid‘,‘testitem‘]),zabbixAPI不会报错,而是默认忽略这个参数,这一点比较坑,需要注意的。

● 主机有一个属性是status,这个属性可以在host.update中使用来实现通过api enable和disable某个主机的操作。但是需要注意的是这个status的值是u‘0‘或者u‘1‘,不是int也不是str,是unicode

● host.update的时候在确定要update哪台主机的时候用的不是filter参数(事实上可能出了get方法以外,其他的用的都不是filter),而是直接有个hostid参数来指定一个hostid,从而确定一台特定的主机。这么做的依据是因为hostid是主机与生俱来且唯一的,可以这么做。。

●host在create的时候可以加上macros参数来添加宏。比如macros=[{‘macro‘:‘{KaTeX parse error: Expected 'EOF', got '}' at position 9: INSTANCE}̲‘,‘value‘:‘fran…ACCOUNT}‘,‘value‘:‘test_account‘}]

参考链接1:https://www.cnblogs.com/franknihao/p/6537439.html
参考链接2:http://blog.51cto.com/4722372/1717410

猜你喜欢

转载自blog.csdn.net/qq_34355232/article/details/83857114
今日推荐