最近,在练习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:p_w_picpath0"></td>
<td><img src="cid:p_w_picpath1"></td>
<td><img src="cid:p_w_picpath8"></td>
</tr>
<td>中间3个图</td>
</tr>
<tr>
<td><img src="cid:p_w_picpath2"></td>
<td><img src="cid:p_w_picpath3"></td>
<td><img src="cid:p_w_picpath7"></td>
</tr>
<td>最后3个图</td>
</tr>
<tr>
<td><img src="cid:p_w_picpath4"></td>
<td><img src="cid:p_w_picpath5"></td>
<td><img src="cid:p_w_picpath6"></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', '<p_w_picpath%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.p_w_picpath 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, ['13434111885@139.com'])

最后,获得如下图形

利用Zabbix通过邮件发送Screen图形报表实现_admin

利用Zabbix通过邮件发送Screen图形报表实现_password_02

利用Zabbix通过邮件发送Screen图形报表实现_import_03

利用Zabbix通过邮件发送Screen图形报表实现_password_04

利用Zabbix通过邮件发送Screen图形报表实现_import_05

利用Zabbix通过邮件发送Screen图形报表实现_python_06

利用Zabbix通过邮件发送Screen图形报表实现_程序_07

利用Zabbix通过邮件发送Screen图形报表实现_程序_08