Python 获取zabbix数据图并发邮件

#! /usr/bin/env python
# coding=utf-8
# Andy_f

import time, os,datetime
import urllib
import urllib2
import cookielib
import MySQLdb
import smtplib
from email.mime.multipart import MIMEMultipart  # 导入MIMEMultipart类
from email.mime.text import MIMEText  # 导入MIMEText类
from email.mime.p_w_picpath import MIMEImage  # 导入MIMEImage类

screens = ["NGINX_flow","mysql"]

now_date = time.strftime("%Y-%m-%d")
save_graph_path = "./weeks/%s" % time.strftime("%Y-%m-%d")
if not os.path.exists(save_graph_path):
    os.makedirs(save_graph_path)

zabbix_host = "zbx.XXXX.com"
username = "Admin"
password = "XXXX&zabbix"
width = 750
height = 200

# graph Time period, s
period = 604800

# zabbix DB
dbhost = "192.168.22.22"
dbport = 3317
dbuser = "XXXX_read"
dbpasswd = "XXXX_read"
dbname = "zabbix"



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)
        if count == 0:
            result = 0
        else:
            result = cur.fetchall()
            return result
        cur.close()
        conn.close()

    except MySQLdb.Error, e:
        print "mysql error:", e


def get_graph(zabbix_host, username, password, screen, width, height, period, save_graph_path):
    for i in mysql_query("select screenid from screens where name='%s'" % (screen)):

        for screenid in i:
            graphid_list = []
            for c in mysql_query("select resourceid from screens_items where screenid='%s'" % (int(screenid))):
                for d in c:
                    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))
                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/%s_%s.png" % (save_graph_path, screenid, graphid)
                f = open(filename, "wb")
                f.write(data)
                f.close()


class SendHtmlMail(object):

    def __init__(self):
        self.HOST = "smtp.exmail.qq.com"
        self.SUBJECT = u"每周官网流量数据报表"
        self.TO = ['xxxx@XXXX.com','XXXX_script@XXXX.com']
        self.FROM = "XXXX_script@XXXX.com"

    def addimg(self,src, imgid):
        fp = open(src, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', imgid)
        return msgImage

    def Send(self):
        msg = MIMEMultipart('related')
        msgtext = MIMEText("""

                        <img>
                        <table width="600" border="0" cellspacing="0" cellpadding="4">
                             <tr  bgcolor="#CECFAD" height="30" >
                                <td  colspan="8" style="text-align: center;font-size: large"> 网贷之家周流量报告(责任人:gaogd) </td>
                             </tr>

                            <tr bgcolor="#EFEBDE" height="100" duokan-code-cn>
                                <td><img src="cid:bbs"></td>
                            </tr>
                             <tr bgcolor="#EFEBDE" height="100"duokan-code-cn>
                                <td><img src="cid:www"></td>
                            </tr>
                            <tr bgcolor="#EFEBDE" height="100"duokan-code-cn>
                                <td><img src="cid:no"></td>
                            </tr>
                            <tr bgcolor="#CECFAD" height="20" duokan-code-cn>
                                <td colspan=2>官方流量报告 <a href="http://zbx.XXXX.com">更多>></a></td>
                            </tr>
                        </table>
                        """, "html", "utf-8")


        msg.attach(msgtext)
        msg.attach(self.addimg("./weeks/%s/36_1904.png"%now_date, "no"))
        msg.attach(self.addimg("./weeks/%s/36_1917.png"%now_date, "www"))
        msg.attach(self.addimg("./weeks/%s/36_1928.png"%now_date, "bbs"))


        msg['Subject'] = self.SUBJECT
        msg['From'] = self.FROM
        msg['To'] = ",".join(self.TO)
        print msg['To']

        try:
            server = smtplib.SMTP()  # 创建一个SMTP()对象
            server.connect(self.HOST, "25")  # 通过connect方法连接smtp主机
            server.starttls()  # 启动安全传输模式
            server.login("XXXX_script@XXXX.com", "XXXXX@*aX")  # 邮箱账号登录校验
            server.sendmail(msg['From'], self.TO, msg.as_string())  # 邮件发送
            server.quit()  # 断开smtp连接
            print "邮件发送成功!"
        except Exception, e:
            print "失败:" + str(e)



if __name__ == '__main__':
    print 'start:: ',datetime.datetime.now()
    now_date = datetime.datetime.now().strftime("%Y-%m-%d")
    for screen in screens:
         get_graph(zabbix_host, username, password, screen, width, height, period, save_graph_path)
    send_obj = SendHtmlMail()
    send_obj.Send()
    print 'stop:: ', datetime.datetime.now()