python獲取zabbix監控項圖形

杨梅杨梅發表於2024-11-25

python獲取zabbix圖形

透過zabbix的api介面獲取指定時間段的監控項圖形
圖片示例:

程式碼示例:

# -*- coding: UTF-8 -*-
#可根據監控項獲取zabbix下所有主機的Itemid,
#透過zabbix庫的graphs_items表 ,獲取graphid
#本文只透過graphid直接獲取圖形

import requests
import datetime

# 配置 Zabbix API 相關引數
ZABBIX_API_URL = "http://xxxxxxxx/zabbix/api_jsonrpc.php"
ZABBIX_USER = "xxxxx"
ZABBIX_PASSWORD = "xxxxx"

# 手動登入 Zabbix 獲取會話 cookie
def zabbix_manual_login():
    session = requests.Session()
    login_url = ZABBIX_API_URL.replace("/api_jsonrpc.php", "/index.php")
    login_payload = {
        "name": ZABBIX_USER,
        "password": ZABBIX_PASSWORD,
        "autologin": 1,
        "enter": "Sign in",
    }
    response = session.post(login_url, data=login_payload)
    if "zbx_sessionid" not in session.cookies:
        raise Exception("登入失敗,請檢查使用者名稱和密碼。")
    return session

# 獲取 Zabbix 圖形圖片
def get_graph_image(session, graphid, start_time, end_time, output_file):
    # 構建圖形 URL
    graph_url = ZABBIX_API_URL.replace("/api_jsonrpc.php", "/chart2.php")
    params = {
        "graphid": graphid,
        "from": start_time,
        "to" : end_time,
        "width": 800,  # 可調整圖形寬度
        "height": 400,  # 可調整圖形高度
        "profileIdx": "web.graphs"
    }

    # 請求圖片
    response = session.get(graph_url, params=params, stream=True)
    if response.headers.get("Content-Type") != "image/png":
        print("獲取圖形失敗,返回內容為:")
        print(response.text)
        raise Exception("未能正確獲取圖形圖片,請檢查引數或許可權。")
    # print(response.text)
    # 儲存圖片到本地
    with open(output_file, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

    print(f"圖形已儲存到 {output_file}")

# 將時間轉換為 Zabbix 的 Unix 時間戳格式
def convert_to_stime(dt):
    return dt.strftime("%Y%m%d%H%M%S")

if __name__ == "__main__":
    try:
        # 手動登入獲取會話
        session = zabbix_manual_login()

        print("登入成功,已獲取會話 cookie。")

        # 指定 graphid
        graphid = "xxxxx"

        # 設定時間範圍(每天的 9 點到 16 點)
        today = datetime.date.today()
        start_time = datetime.datetime(today.year, today.month, today.day, 9, 0, 0)
        end_time = datetime.datetime(today.year, today.month, today.day, 16, 0, 0)
        # 儲存圖片的檔案路徑
        output_file = f"zabbix_graph_{graphid}.png"

        # 獲取圖形圖片
        get_graph_image(session, graphid, start_time, end_time, output_file)

    except Exception as e:
        print("發生錯誤:", str(e))

相關文章