python2.7调用zabbixAPI接口实现获取监控项的历史数据

#!/usr/bin/env python
# coding:utf-8
import json

apiURL = "http://xx.xx.xx.xx/api_jsonrpc.php"

header = {"Content-Type": "application/json"}

zabbix_key = "XXXXXXXXXXXXXXXXXXXXXXX"

# 获取监控的每个组名字及其ID
# data = json.dumps(
#     {
#         "jsonrpc": "2.0",
#         "method": "hostgroup.get",
#         "params": {
#             "output": ["groupid", "name"],
#         },
#         "auth": zabbix_key,
#         "id": 1,
#     })

# 获取单个组天津下监控的每台主机
data1 = json.dumps(
    {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["hostid", "name"],
            "groupids": "43",
        },
        "auth": zabbix_key,
        "id": 1,
    })

# 获取单个主机下的所有监控项
# data2 = json.dumps(
#     {
#         "jsonrpc": "2.0",
#         "method": "item.get",
#         "params": {
#             "output": ["itemids", "key_"],
#             "hostids": "16826",
#         },
#         "auth": zabbix_key,
#         "id": 1,
#     })

# 获取单个监控项下的历史数据
# data3 = json.dumps(
#     {
#         "jsonrpc": "2.0",
#         "method": "history.get",
#         "params": {
#             "output": "extend",
#             "history": 3,
#             "itemids": "101684",
#             "sortfield": "clock",
#             "sortorder": "DESC",
#             "limit": 20
#         },
#         "auth": zabbix_key,
#         "id": 1,
#     })

 

#!/usr/bin/env python
# coding:utf-8
import time
import json
import urllib2
from urllib2 import URLError
from conf import apiURL
from conf import header
from conf import data1
from conf import zabbix_key


# 这个Item类的实例方法get_hh主要实现了向zabbixapi发送请求获取数据的功能,这个功能保持不变,根据传入的data参数,获取结果不同。
class Item:
    def get_hh(self, data):

        request = urllib2.Request(apiURL, data)

        for key in header:
            request.add_header(key, header[key])

        try:
            result = urllib2.urlopen(request)

        except URLError as e:

            if hasattr(e, 'reason'):

                print 'We failed to reach a server.'

                print 'Reason:', e.reason

            elif hasattr(e, 'code'):

                print 'The server could not fulfill the request.'

                print 'Error code:', e.code

        else:
            response = json.loads(result.read())

            result.close()

            return response['result']


# 获取主机列表hostid、hostid与服务器对应关系
def get_hosts():
    p = Item()
    lst = []  # hostids
    dic = {}  # 对应关系
    for host in p.get_hh(data1):
        # print host['hostid'],host['name']
        dic[host['hostid']] = host['name']
        lst.append(host['hostid'])
    return lst, dic


# 获取每台服务器的hostid、服务器ip地址、监控项id、服务器的监控项
def get_items():
    hostids, ral = get_hosts()
    p1 = Item()
    items = []
    for hostid in hostids:
        data2 = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "item.get",
                "params": {
                    "output": ["itemids", "key_"],
                    "hostids": hostid,
                    "search": {
                        "key_": "xxxxxxxx"
                    },
                },
                "auth": zabbix_key,
                "id": 1,
            })
        # 判断这个key是否为空,不为空则加入列表
        if p1.get_hh(data2):
            items.append((hostid, ral[hostid], p1.get_hh(data2)))
    return items


# 获取每台服务器下gll的历史数据
def get_history():
    items = get_items()
    p2 = Item()
    for ss in items:
        data3 = json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "history.get",
                "params": {
                    "output": "extend",
                    "history": 5,
                    "itemids": ss[2][0]['itemid'],
                    "sortfield": "clock",
                    "sortorder": "DESC",
                    "limit": 20
                },
                "auth": zabbix_key,
                "id": 1,
            })
        host = p2.get_hh(data3)
        for i in host:
            timeStamp = int(i['clock'])
            timeArray = time.localtime(timeStamp)
            clock = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            print clock, ss[1], i['value']


get_history()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值