Python 获取zabbix数据图并发邮件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 获取zabbix数据图并发邮件相关的知识,希望对你有一定的参考价值。


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.image 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 = [‘[email protected]‘,‘XXXX_[email protected]‘]
        self.FROM = "[email protected]"

    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("[email protected]", "[email protected]*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()


本文出自 “奋斗吧” 博客,请务必保留此出处http://lvnian.blog.51cto.com/7155281/1882765

以上是关于Python 获取zabbix数据图并发邮件的主要内容,如果未能解决你的问题,请参考以下文章

zabbix配置邮件告警

提取zabbix监控平台单台服务器图形并发邮件python实现

在服务器上使用python自动获取zabbix上图形并发送邮件

zabbix的添加自定义监控项目配置邮件告警测试告警

Zabbix告警发送性能图

Python3 - 监控CentOS磁盘空间&预警发送邮件