利用Zabbix通過郵件發送Screen圖形報表實現

最近,在練習python程序,心血來潮,想利用zabbix-API來實現Zabbix通過郵件發送Screen圖形報表,以便預測故障的發生,直接上源碼,本人菜鳥,程序有爛的地方,請各位高手原諒。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys
import time
import shutil
import MySQLdb
import smtplib
import requests
import datetime
import urllib
import urllib2
import cookielib
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
# based on zabbix 2.4.4
zabbix_host = '127.0.0.1'
username = 'admin'
password = 'zabbix'
width = 400
height = 156
period = 86400
dbhost = 'localhost'
dbuser = 'zabbix'
dbpasswd = 'zabbix'
dbname = 'zabbix'
dbport = '3306'
GRAPH_PATH = '/tmp/zabbix_graph'
EMAIL_DOMAIN = '139.com'
EMAIL_USERNAME = '13434111885'
EMAIL_PASSWORD = 'p@ssw0rd'

recipients = ["/home/*.jpeg"]

graphid_list = []

def SQL_Exec(query):
    try:
        _Conn = MySQLdb.connect(host='localhost',user='zabbix',passwd='zabbix',port=3306,connect_timeout=20)
        _Conn.select_db(dbname)
        cur = _Conn.cursor()
        _Conn = cur.execute(query)
        if _Conn == 0:
            result = 0
        else:
            result = cur.fetchall()
        return result
        cur.close()
        _Conn.close()
    except MySQLdb.Error,e:
        print "mysql error:" ,e

def Save_Graph(zabbix_host,username,password,width,height,period):
    for c in SQL_Exec("select resourceid from screens_items where screenid='20'"):
        for d in c:
            graphid_list.append(int(d))
    for graphid in graphid_list:
        print graphid
        login_opt = urllib.urlencode({
        "name": username,
        "password": password,
        "autologin": 1,
        "enter": "Sign in"})
        get_graph_opt = urllib.urlencode({
        "graphid": graphid,
        "screenid": '16',
        "width": width,
        "height": height,
        "period": period})
        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        login_url = r"http://%s/index.php"%zabbix_host
        save_graph_url = r"http://%s/chart2.php"%zabbix_host
        opener.open(login_url,login_opt).read()
        data = opener.open(save_graph_url,get_graph_opt).read()
        filename = "%s.jpeg"%str(graphid)
        f = open(filename,"wb")
        f.write(data)
        f.close()
def send_mail(screen_name, graphs, to_list):
  me = 'Zabbix <%s@%s>' % (EMAIL_USERNAME, EMAIL_DOMAIN)
  def _create_msg():
    msg = MIMEMultipart('related')
    msg['Subject'] = 'Zabbix Screen Report: %s' % screen_name
    msg['From'] = me
    msg['To'] = ';'.join(to_list)
    msg.preamble = 'This is a multi-part message in MIME format.'
    contents = "<h1>Screen %s</h1><br>" % screen_name
    contents += "<table>"

    zbxText = MIMEText("""
<strong>內容</strong><br /><br />
<table border="0">
<tr>
<td>前3個圖</td>
</tr>
<tr>
<td><img src="cid:image0"></td>
<td><img src="cid:image1"></td>
<td><img src="cid:image8"></td>
</tr>
<td>中間3個圖</td>
</tr>
<tr>
<td><img src="cid:image2"></td>
<td><img src="cid:image3"></td>
<td><img src="cid:image7"></td>
</tr>
<td>最後3個圖</td>
</tr>
<tr>
<td><img src="cid:image4"></td>
<td><img src="cid:image5"></td>
<td><img src="cid:image6"></td>
</tr>
</table>
    """,'html','utf-8')
    msg.attach(zbxText)

    for n in range(len(graphid_list)):
        zbx_img = open(r'%s.jpeg'%graphid_list[n], 'rb')
        msgImage = MIMEImage(zbx_img.read())
        zbx_img.close()
        msgImage.add_header('Content-ID', '<image%s>'%n)
        msg.attach(msgImage)
    msg_text = MIMEText(contents, 'html')
    msg_alternative = MIMEMultipart('alternative')
    msg_alternative.attach(msg_text)
    msg.attach(msg_alternative)
    return msg
  try:
    server = smtplib.SMTP()
    server.connect('smtp.%s' % EMAIL_DOMAIN)
    server.login('%s@%s' % (EMAIL_USERNAME, EMAIL_DOMAIN), EMAIL_PASSWORD)
    server.sendmail(me, to_list, _create_msg().as_string())
    server.close()
    print 'send mail Ok!'
  except Exception, e:
    print e
if __name__ == '__main__':
    import sys,re,os,smtplib
    from email.MIMEText import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email import Utils,Encoders
    Save_Graph(zabbix_host,username,password,width,height,period)
    send_mail(Save_Graph, recipients, ['[email protected]'])

最後,獲得如下圖形

wKioL1ZyOWGQKacsAABzUF2HcZg656.png

wKioL1ZyOWKzsYGuAACMMGyXBWs755.png

wKioL1ZyOWPCyky8AABJfF0SuLc880.png

wKioL1ZyOWTQwgB6AABZ0jcvE5Y949.png

wKiom1ZyOVvR1_nTAABvXNiGfN0654.png

wKiom1ZyOVvA7b6uAABudx2k414849.png

wKioL1ZyOWaTFsGlAABs8Bmx7sQ376.png

wKioL1ZyOWeCTTVtAAB6AeP7qv0381.png


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章