Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python 讓 Zabbix 自動把監控圖表寄到信箱

Zabbix 的 screens 通常放的是管理員最關心的監控指標。既然已經有人精心整理過,不如讓程式每天自動把這些圖截下來、包成 HTML 信寄進收件匣,上班第一件事就能看。

先拆解圖片網址

在 screen 上對任一張圖按右鍵「複製圖片網址」,會得到一長串參數:

https://zabbix.xxx.com/chart2.php?graphid=524&screenid=16&width=400&height=156&updateProfile=1&profileIdx=web.screens&profileIdx2=16&period=86400&stime=20150629172712&sid=f6dd0d127bba0123&curtime=1404120808037

其實真正必要的只有五個:

graphid   # 圖表唯一 ID
screenid  # screen 唯一 ID
width     # 圖寬,自訂
height    # 圖高,自訂
period    # 取數時間窗,單位秒(86400 = 1 天)

簡化後就是:

https://zabbix.xxx.com/chart2.php?graphid=524&screenid=16&width=400&height=156&period=86400

參數從哪裡來?查 Zabbix 的資料庫

  1. 用管理員自訂的 screen 名稱,在 screens 表查出 screenid。
  2. 用 screenid 在 screens_items 表查出各 resourceid(即 graphid)。
  3. 帶著這些參數抓圖,存到 Zabbix 伺服器的 web 目錄,並組出 HTML。
  4. 用 smtplib 把 HTML 信寄給管理員。

程式碼

#! /usr/bin/env python
#coding=utf-8
import time, os, urllib, urllib2, cookielib, smtplib
import MySQLdb
from email.mime.text import MIMEText

screens = ["xxx", "xxx"]
save_graph_path = "/var/www/zabbix/reports/%s" % time.strftime("%Y-%m-%d")
if not os.path.exists(save_graph_path):
    os.makedirs(save_graph_path)

zabbix_host = "zabbix.xxx.com"
username, password = "admin", "zabbix"
width, height, period = 600, 100, 86400

dbhost, dbport = "xxx.xxx.xxx.xxx", 3306
dbuser, dbpasswd, dbname = "zabbix", "xxxxx", "zabbix"

to_list = ["xxx@xxx.com", "aaa@xxx.com"]
smtp_server, mail_user, mail_pass = "smtp.163.com", "xxxx", "xxxxx"
domain = "163.com"

def mysql_query(sql):
    try:
        conn = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpasswd,
                               port=dbport, connect_timeout=20)
        conn.select_db(dbname)
        cur = conn.cursor()
        count = cur.execute(sql)
        result = 0 if count == 0 else cur.fetchall()
        cur.close(); conn.close()
        return result
    except MySQLdb.Error, e:
        print "mysql error:", e

def get_graph(screen):
    global html
    html = ''
    for row in mysql_query("select screenid from screens where name='%s'" % screen):
        for screenid in row:
            graphid_list = []
            for r in mysql_query("select resourceid from screens_items where screenid='%s'" % int(screenid)):
                for d in r:
                    graphid_list.append(int(d))
            for graphid in graphid_list:
                login_opt = urllib.urlencode({
                    "name": username, "password": password,
                    "autologin": 1, "enter": "Sign in"})
                get_graph_opt = urllib.urlencode({
                    "graphid": graphid, "screenid": screenid,
                    "width": width, "height": height, "period": period})
                cj = cookielib.CookieJar()
                opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
                opener.open(r"https://%s/index.php" % zabbix_host, login_opt).read()
                data = opener.open(r"https://%s/chart2.php" % zabbix_host, get_graph_opt).read()
                filename = "%s/%s.%s.png" % (save_graph_path, screenid, graphid)
                html += '<img width="600" height="250" src="https://%s/reports/%s/%s.%s.png">' % (
                    zabbix_host, time.strftime("%Y-%m-%d"), screenid, graphid)
                f = open(filename, "wb"); f.write(data); f.close()

def send_mail(sub, content):
    me = "運維<" + mail_user + "@" + domain + ">"
    msg = MIMEText(content, _subtype="html", _charset="utf8")
    msg["Subject"], msg["From"] = sub, me
    msg["To"] = ";".join(to_list)
    try:
        server = smtplib.SMTP()
        server.connect(smtp_server)
        server.login(mail_user, mail_pass)
        server.sendmail(me, to_list, msg.as_string())
        server.close()
        print "send mail Ok!"
    except Exception, e:
        print e

if __name__ == '__main__':
    for screen in screens:
        get_graph(screen)
    send_mail("test email", html)

注意登入是靠 cookielib 保存 session,再拿同一個 opener 去抓 chart2.php,少了這步只會拿到登入頁。

掛上排程

crontab -e
45 08 * * * python /root/zabbix_send_report.py

每天早上 8:45 自動寄出,圖片同時留在 web 目錄,需要回看歷史直接開網址即可。

Copyright © Linux教程網 All Rights Reserved