萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Zabbix API 取得監控資料完整實作:從認證到歷史數據擷取

透過 Zabbix API 取代直接查資料庫,靈活獲取監控數據供 RRDtool 繪圖或其他用途。核心流程:登入取 Token → 取所有主機 → 遍歷每主機圖形 → 取圖形監控項 → 取最新值或歷史值。

1. 登入取得認證 Token

class Zabbix:
    def __init__(self):
        self.url = "https://xxx.xxx.xxx.xxx:xxxxx/api_jsonrpc.php"
        self.header = {"Content-Type": "application/json"}
        self.authID = self.user_login()

    def user_login(self):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {"user": "用戶名", "password": "密碼"},
            "id": 0
        })
        req = urllib2.Request(self.url, data)
        for k, v in self.header.items(): req.add_header(k, v)
        try:
            resp = json.loads(urllib2.urlopen(req).read())
            return resp['result']
        except URLError as e:
            print("Auth Failed:", e.code if hasattr(e,'code') else e.reason)
            return 0

2. 通用請求封裝

def get_data(self, data):
    req = urllib2.Request(self.url, data)
    for k, v in self.header.items(): req.add_header(k, v)
    try:
        return json.loads(urllib2.urlopen(req).read())
    except URLError as e:
        print("Request Error:", e.code if hasattr(e,'code') else e.reason)
        return 0

3. 取得所有主機

def hostsid_get(self):
    data = json.dumps({
        "jsonrpc": "2.0", "method": "host.get",
        "params": {"output": ["hostid", "status", "host"]},
        "auth": self.authID, "id": 1
    })
    res = self.get_data(data)['result']
    hosts = []
    for h in res:
        if h['status'] in ('0','1'):  # 0=啟用 1=停用 皆納入
            hosts.append({h['host']: h['hostid']})
    return hosts  # 列表套字典: [{hostname: hostid}, ...]

4. 取得主機所有圖形

def hostgraph_get(self, hostname):
    data = json.dumps({
        "jsonrpc": "2.0", "method": "host.get",
        "params": {"selectGraphs": ["graphid", "name"], "filter": {"host": hostname}},
        "auth": self.authID, "id": 1
    })
    return self.get_data(data)['result'][0]['graphs']  # 列表套字典

5. 取得圖形監控項與最新值

def graphitems_get(self, graphid):
    data = json.dumps({
        "jsonrpc": "2.0", "method": "graphitem.get",
        "params": {"output": "extend", "graphids": graphid},
        "auth": self.authID, "id": 1
    })
    res = self.get_data(data)['result']
    items = []
    for v in res:
        # 處理含巨集的名稱 (如 $1)
        if '$' in v['name']:
            # ... 解析 key_ 中參數替換巨集 ...
            pass
        items.append({
            'itemid': v['itemid'], 'delay': v['delay'],
            'units': v['units'], 'name': v['name'],
            'value_type': v['value_type'],
            'lastclock': v['lastclock'], 'lastvalue': v['lastvalue']
        })
    return items

6. 取得歷史數據 (最近 10 筆)

def history_get(self, itemid, history_type):
    # history_type: 0=float, 1=str, 2=log, 3=uint, 4=text
    data = json.dumps({
        "jsonrpc": "2.0", "method": "history.get",
        "params": {"output": "extend", "history": history_type,
                   "itemids": itemid, "sortfield": "clock",
                   "sortorder": "DESC", "limit": 10},
        "auth": self.authID, "id": 1
    })
    return self.get_data(data)['result']

以上類別封裝完整,可直接整合至監控平台或繪圖系統。

copyright © 萬盛學電腦網 all rights reserved