• Zabbix Web API Get方法整合


    #!/usr/bin/python3

    import requests,json,re,time,datetime
     
     
    url = 'http://xxx.com/api_jsonrpc.php'
    headers = {"Content-Type":"application/json"'User-Agent''Godaner.com python-requests'#设置请求头
    username = 'username'     #用户名
    password = 'passwd'        #密码
     
    def get_token():            #获取认证token,token有效时间为zabbix用户配置的自动退出时间
        data = {
            "jsonrpc""2.0",
            "method""user.login",
            "params": {
                "user": username,
                "password": password
            },
            "id"0
        }
        try:
            resp = requests.post(url=url, headers=headers, data=json.dumps(data))
            token = json.loads(resp.text)['result']
            #resp.close()
        except:
            return 'F'
        return token
    #示例获取token 
    token = get_token()
    print(token)
    f24008481e287qc1e931e6598c041od6
     
     
    def get_host(token,ip2host=""):
        if ip2host:
            selectItems = "selectItems"
            selectTriggers = "selectTriggers"
        else:
            selectItems = ""
            selectTriggers = ""
        if re.search('[a-z]', ip2host):
            arg = 'host'
        else:
            arg = 'ip'
        #获取单个或者所有zabbix主机信息,ip2host(IP,主机名)为空获取所有主机信息
        #获取所有主机的时候将不输出对应主机的监控项和触发器信息。(大量主机)
        data = {
            "jsonrpc""2.0",
            "method""host.get",
            "params": {
                "output": ["hostid","name","status","available"],
                #返回: [主机id,主机名,主机状态(0监控中|1未监控),主机的可用性(0可用|1不可用)]
                selectItems: ["itemid","key_","name","value_type","status","lastclock","lastvalue"],
                #返回此主机的监控项信息:[id,key,名称,数据类型,可用性(0 启用|1 禁用),上次取值时间,最后一次的值]
                #特别注意value_type,这个参数是创建监控项时,选择的返回值数据类型。当获取不到item值的时候,要注意此值:
                #0 浮点数;1 字符串;2 日志;3 整数 默认值;4 文本长字符串
                selectTriggers: ["expression","priority","status","value"],
                #返回此主机的触发器信息:[触发器表达式,严重级别(0-5),可用性(0 启用|1 禁用),触发器状态(0 正常|1 问题)]
                "selectGroups": ["groupid","name"],
                #返回此主机所在组:[组id,组名]
                "selectInterfaces": ["interfaceid","ip","port"],
                #返回此主机连接信息:[网卡id,ip地址,端口]
                "selectParentTemplates": ["templateid","name"],
                #返回此主机连接的模板信息:[模板id,模板名]
                "filter": {
                    arg: ip2host,
                },
                #过滤,这个跟上面的逻辑对应,这里过滤ip或者主机名,只在ip2host参数有值时生效
            },
        "id"0,
        "auth": token,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取所有主机和单个主机,单个主机的时候返回监控项和触发器信息
    hosts = get_host(token)    #获取所有主机信息
    print(json.dumps(hosts, indent=4, ensure_ascii=False))
    [    
        {
            "status""0",
            "name""xxxxxxxxxx",
            "hostid""14700"
            "available""1",
            "parentTemplates": [
                {
                    "templateid""12601",
                    "name""Agent_SH"
                },
                {
                    "templateid""13025",
                    "name""Template_Apps"
                }
            ],
            "interfaces": [
                {
                    "interfaceid""4771",
                    "ip""xx.xx.xx.xx",
                    "port""10050"
                }
            ],
            "groups": [
                {
                    "name""Discovered hosts",
                    "groupid""5"
                },
                {
                    "name""OS_CentOS",
                    "groupid""15"
                }
            ],
        },
        {
            "status""0",
            "name""xxxxxxxxxx",
            "hostid""14701"
            "available""1",
            "parentTemplates": [
                {
                    "templateid""12601",
                    "name""Agent_SH"
                },
                {
                    "templateid""13025",
                    "name""Template_Apps"
                }
            ],
            "interfaces": [
                {
                    "interfaceid""4834",
                    "ip""xx.xx.xx.xx",
                    "port""10050"
                }
            ],
            "groups": [
                {
                    "name""Discovered hosts",
                    "groupid""5"
                },
                {
                    "name""OS_CentOS",
                    "groupid""15"
                }
            ],
        },   
        ······
    ]
    host = get_host(token,ip2host='x.x.x.x')    #获取单个主机信息,带项目和触发器信息
    print(json.dumps(host, indent=4, ensure_ascii=False))
    [
        {
            "interfaces": [
                {
                    "ip""x.x.x.x",
                    "interfaceid""1",
                    "port""10050"
                }
            ],
            "name""Godaner",
            "items": [
                {
                    "name""check iptables",
                    "lastvalue""it's ok",
                    "key_""fwcheck",
                    "value_type""4",
                    "itemid""23833",
                    "lastclock""1554515244",
                    "status""0"
                },
                {
                    "name""login",
                    "lastvalue""Apr 5 16:43:37 Godaner sshd[24987]: Accepted password for ····",
                    "key_""log[/var/log/secure,"Accepted password",,,skip,]",
                    "value_type""2",
                    "itemid""23767",
                    "lastclock""1554453825",
                    "status""0"
                },          
                ······
            ],
            "triggers": [
                {
                    "value""0",
                    "status""0",
                    "priority""5",
                    "expression""{13220}=0 and {13221}=0",
                    "triggerid""13614"
                },
                {
                    "value""0",
                    "status""0",
                    "priority""4",
                    "expression""{13299}>1",
                    "triggerid""13616"
                },           
                ······
            ],
            "hostid""10084",
            "groups": [
                {
                    "name""testgroup",
                    "groupid""4"
                }
            ],
            "available""1",
            "status""0"
        }
    ]
     
     
    def get_trigger_bad(token,hostid=""): 
        if not hostid:
            arg = ""
        else:
            arg = "hostids"
        #获取问题触发器,hostid为空时,获取所有问题触发器
        data = {
            "jsonrpc""2.0",
            "method""trigger.get",
            "params": {
                arg: hostid,
                "only_true"1,         #只返回最近处于问题状态的触发器
                "active"1,            #只返回启用的触发器
                #"skipDependent":1,     #在依赖于其他触发器的问题状态中跳过触发器
                "monitored":1,          #只返回所属被监控主机启用触发器,且包含已启用的监控项(跳过监控项不可用的问题触发器)
                "output": ["priority","status","value","description"],
                #输出: [严重级别|(启用|禁用)|(正常|问题)|触发器名称]
                "selectHosts": ["name"],#返回host,id
                #"selectItems": ["name"],#返回item,id
                "sortfield""priority",#以严重级别排序
                "sortorder""DESC",    #降序 
                "filter": {
                   "value"1,         #过滤问题触发器
                }
            },
        "id"0,
        "auth": token,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取当前所有问题触发器
    trigger_bad = get_trigger_bad(token)
    print(json.dumps(trigger_bad, indent=4, ensure_ascii=False))
    [
        {
            "description""Filesystems: 可用磁盘空间少于 5% --> /usr",
            "hosts": [
                {
                    "hostid""13382",
                    "name""x.x.x.x"
                }
            ],
            "priority""2",
            "value""1",
            "triggerid""77341",
            "status""0"
        },
        {
            "description""zombie on {HOST.NAME}",
            "hosts": [
                {
                    "hostid""11820",
                    "name""x.x.x.x"
                }
            ],
            "priority""1",
            "value""1",
            "triggerid""63834",
            "status""0"
        },    
        ······    
    ]
     
     
    def get_groups(token):  #获取所有组信息,输出组id,组名
        data = {
            "jsonrpc""2.0",
            "method""hostgroup.get",
            "params": {
               "output": ["groupid","name"],
            },
            "auth": token,
            "id"0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取所有组
    groups = get_groups(token)
    print(json.dumps(groups, indent=4, ensure_ascii=False))
    [
        {
            "name""SH",
            "groupid""49"
        },
        {
            "name""HK",
            "groupid""4"
        },
        ······
    ]
     
     
    def get_group_hosts(token, groupid):    #获取指定组id里的所有主机,输出主机名跟id
        data = {
            "jsonrpc""2.0",
            "method""host.get"
            "params": {
                "groupids": groupid,
                "output": ["host","hostid"],
            },
            "auth": token,
            "id"0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取指定组里所有主机
    hosts = get_group_hosts(token,groupid='xxx')
    print(json.dumps(hosts, indent=4, ensure_ascii=False))
    [
        {
            "host""web.zabbix",
            "hostid""13247"
        },
        {
            "host""db.zabbix",
            "hostid""14045"
        },
        ······
    ]
     
     
    def get_items(token, hostid, key=""): #获取指定主机所有监控项,也可指定key名称获取。 
        if re.search('[a-z]', key):
            arg = "key_"
        else:
            arg = "itemid"
        data = {
            'jsonrpc''2.0',
            'method'"item.get",
            "params": {
                "output": ["itemid","key_","name","value_type","status","lastclock","lastvalue"],
                #输出信息跟上面的get_host里的selectItems一样
                "hostids": hostid,
                "filter":{
                    arg: key,
                },
            },
            'auth': token,
            'id'0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取单个主机所有监控项
    itemids = get_items(token,hostid='xxxx')
    print(json.dumps(itemids, indent=4, ensure_ascii=False))
    [
        {
            "lastclock""1554514630",
            "value_type""3",
            "key_""vm.memory.size[total]",
            "name""Total memory",
            "itemid""23830",
            "lastvalue""17180569600",
            "status""0"
        },
        {
            "lastclock""1554517503",
            "value_type""3",
            "key_""webcheck",
            "name""check www.godaner.com",
            "itemid""23832",
            "lastvalue""200",
            "status""0"
        },
        ······
    ]
     
     
    def get_history(token, itemid, limit="10", stime="", etime="", vtp="3"):
        #get_history(token=get_token(),itemid='23809')返回指定监控项23809最近10条数据
        #如果没有值,注意vtp,默认是整数型的,比如要取cpu load的值,就要用vtp=0
        if not etime:
            etime = time.time()
        #不指定结束时间,结束之间为当前时间,也可指定时间段查询,单位为时间戳
        data = {
            "jsonrpc""2.0",
            "method""history.get",
            "params": {
                "output""extend",     #输出所有
                "history": vtp,         #值存储的数据类型
                "itemids": itemid,      #itemid
                "sortfield""clock",   #以时间排序
                "sortorder""DESC",    #倒序
                "limit": limit,         #返回数据的条数
                "time_from": stime,     #返回在给定时间时或之后收到的值
                "time_till": etime,     #返回在给定时间时或之前收到的值
            },
            "auth": token,
            "id"0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取单个item最近10次的历史记录,也可指定某个时间段,此例为默认
    history = get_history(token,itemid='23832')
    print(json.dumps(history, indent=4, ensure_ascii=False))
    [
        {
            "itemid""23832",
            "ns""670291350",
            "clock""1554516780",
            "value""200"
        },
        {
            "itemid""23832",
            "ns""41115479",
            "clock""1554516660",
            "value""502"
        },
        ······
    ]
     
     
    def get_events(token,tfrom):
        #某个时间之后,由问题触发器产生的事件
        data = {
            "jsonrpc""2.0",
            "method""event.get",
            "params": {
                "output": ["eventid","clock","value"],
                #返回:[事件id,事件,
                #"value这个值是相关对象状态,这个值可能来自于触发器,可能是自动发现,还有可能是内部事件,记住1是问题就行"]
                #"time_from": time.mktime((datetime.datetime.now() - datetime.timedelta(days=1)).timetuple()),
                "time_from": tfrom,         #返回这个时间戳之后的事件
                "selectHosts": ["name"],    #返回这个事件是哪个主机产生的
                "selectRelatedObject": ["triggerid","description"],
                #返回这个事件是哪个对象产生的,如果是触发器的话返回[触发器id,触发器名称]
                "sortfield": ["clock"],     #以时间排序
                "sortorder""desc",        #倒序
                "filter": {                 #过滤
                    "source""0",          #0 触发器,1 自动发现,2 自动注册,3内部事件
                    "object""0",          #0,1,2,3 同上,0就是触发器事件
                    "value""1",           #0 正常事件,1 故障事件
                }
            },
        "auth": token,
        "id"0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取某个时间之后,所有由问题触发器产生的事件
    events = get_events(token,tfrom='1554315660')
    print(json.dumps(events, indent=4, ensure_ascii=False))
    [
        {
            "eventid""10375",
            "hosts": [
                {
                    "name""Godaner",
                    "hostid""10084"
                }
            ],
            "clock""1554374074",
            "relatedObject": {
                "triggerid""13654",
                "description""check www.godaner.com"
            },
            "value""1"
        },
        {
            "eventid""10376",
            "hosts": [
                {
                    "name""Godaner",
                    "hostid""10084"
                }
            ],
            "clock""1554374194",
            "relatedObject": {
                "triggerid""13654",
                "description""check www.godaner.com"
            },
            "value""1"
        },
        ······
    ]
     
     
    def get_alerts(token,tfrom):
        #获取报警信息
        data = {
            "jsonrpc""2.0",
            "method""alert.get",
            "params": {
                "output": ["eventid","subject","clock","esc_step"],
                #输出:[事件id,报警主题,报警时间,
                #警次次数,这个报警次数是针对单事件的,多事件报警这个值永远为1。多事件就是在创建触发器那里有个多事件选择
                #这个值就可以很好的判断 这个报警持续了多久 重要哦]
                "time_from": tfrom,
                #返回这个时间戳之后的报警,上面这个是1天(24小时)前的时间戳
                "selectHosts": ["name"],    #返回报警主机的主机名
                "sortfield": ["clock"],     #以时间排序
                "sortorder""desc",        #倒序
            },
            "auth": token,
            "id"0,
        }
        resp = requests.post(url=url, headers=headers, data=json.dumps(data))
        return json.loads(resp.text)['result']
    #示例 获取24小时内报警信息
    tt = time.mktime((datetime.datetime.now() - datetime.timedelta(days=3)).timetuple())
    alerts = get_alerts(token,tfrom=tt)
    print(json.dumps(alerts, indent=4, ensure_ascii=False))
    [
        {
            "clock""1554374317",
            "esc_step""3",
            "subject""Godaner: check www.godaner.com",
            "hosts": [
                {
                    "hostid""10084",
                    "name""Godaner"
                }
            ],
            "eventid""10376",
            "alertid""10129"
        },
        {
            "clock""1554374317",
            "esc_step""3",
            "subject""Godaner: check www.godaner.com",
            "hosts": [
                {
                    "hostid""10084",
                    "name""Godaner"
                }
            ],
            "eventid""10376",
            "alertid""10130"
        },
        ······
    ]
  • 相关阅读:
    Linux下Nginx服务Rewrite和Proxy_Pass
    nginx配置中proxy_redirect的作用(转)
    nginx location rewrite常用详解
    Nginx URL重写(rewrite)配置及信息详解
    Selenium上传文件
    Selenium测试Ajax应用程序中的主要问题
    Selenium得到当前页面的URL
    Selenium高亮页面对象
    Selenium简单测试页面加载速度的性能(Page loading performance)
    Selenium Page object Pattern usage
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/10661176.html
Copyright © 2020-2023  润新知