码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-02-18 17:00:50      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:包含   url   pytho   from   数据   build   screen   mem   turn   

由于某些需求,需要每天发送邮件给相关人员,其中包含前一天的zabbix监控图形,每天登陆并手动发送的话很麻烦。

本着简单重复的工作交给机器做的原则,写了个python程序自动获取图形并发送。

大致的思路是:

  模拟登陆zabbix ---> 找到需要的图像并下载到本地 --->使用python发送邮件

一、在服务器上模拟登陆zabbix,并且将需要的图像下载到本地

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

import HTMLParser
import urlparse
import urllib
import urllib2
import cookielib
import string
import os

# 登录的主页面
hosturl = http://zabbix.example.com/screens.php?elementid=26&sid=fbc2974a32b8dc87  # 根据自己的实际地址填写
# post数据接收和处理的页面(我们要向这个页面发送我们构造的Post数据)
posturl = http://zabbix.example.com/index.php  # 从数据包中分析出,处理post请求的url

# 设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)

# 打开登录主页面(他的目的是从页面下载cookie,这样我们在再送post数据时就有cookie了,否则发送不成功)
h = urllib2.urlopen(hosturl)

# 构造header,一般header至少要包含一下两项。这两项是从抓到的包里分析得出的。
headers = {User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1,
           Referer: ******}
# 构造Post数据,他也是从抓大的包里分析得出的。
postData = {
    name: username,    # 用户名
    password: passwd,   # 密码
    autologin: 1,
    enter: Sign in
}

# 需要给Post数据编码
postData = urllib.urlencode(postData)

# 通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程
request = urllib2.Request(posturl, postData, headers)
response = urllib2.urlopen(request)
text = response.read()


def get_graph(host, graphid, period, image_name):
    
    path = /opt/daily_mail/image/  # 保存图片的地址
    #zabbix的图片的地址的构造
    url = "http://%s/chart2.php?graphid=%s&period=%s&width=800&height=100" % (host, graphid, period)

    img_req = urllib2.Request(url)
    png = urllib2.urlopen(img_req).read()

    file = path + image_name + .png
    with open(file,wb) as f:
        f.write(png)

host = zabbix.example.com    // 你的zabbix服务域名
get_graph(host, 1237, 86400, cpu_load)
get_graph(host, 1239, 86400, net_traffic)
get_graph(host, 918, 86400, 155_eth0)

二、将图像下载到本地之后,需要再使用python来自动发送邮件,网上有很多发送邮件的教程

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

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import data
import time

mailto_list=[xxx@example.com]   # 收件人列表
mailcc_list=[xxx@example.com]   # 抄送列表
mail_host="smtp.example.com:25"   # 邮件服务器
mail_user="username"              # 用户名
mail_pass="passwd"                # 密码
mail_postfix="example.com"        #  邮件后缀

html = """<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<p>
服务器 CPU user time 的24h截图<br>
<img src="cid:cpu_load" />
</p>
<p>
服务器 net outging 的24h截图<br>
<img src="cid:net_traffic" />
</p>
<p>
服务器 eth0 24h出口带宽 的24h截图<br>
<img src="cid:155_eth0" />
</p>
"""

def send_mail(to_list, cc_list, sub):
    # 增加图片
    def addimg(src, imgid):
        fp = open(src, rb)
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header(Content-ID, imgid)
        return msgImage

    msg = MIMEMultipart(related)
    #HTML代码
    msgtext = MIMEText(data.html, "html", "utf-8")
    msg.attach(msgtext)

    # 全文件路径,后者为ID 根据ID在HTML中插入的位置
    msg.attach(addimg("/opt/daily_mail/image/cpu_load.png", "cpu_load"))
    msg.attach(addimg("/opt/daily_mail/image/net_traffic.png", "net_traffic"))
    msg.attach(addimg("/opt/daily_mail/image/155_eth0.png", "155_eth0"))

    me = mail_user + "@" + mail_postfix 
    msg[Subject] = sub
    msg[From] = me
    msg[To] = ",".join(to_list)
    msg[Cc] = ",".join(cc_list)
    send_to = to_list + cc_list
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user, mail_pass)
        server.sendmail(me, send_to, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False

if __name__ == __main__:
    title = "zabbix监控数据" + time.strftime(%Y%m%d,time.localtime(time.time()))
    if send_mail(mailto_list, mailcc_list, title):
        print "发送成功"
    else:
        print "发送失败"

就是这么简单,发送的样品就不截图了

模拟登陆那块有参照网上博客,太久不记得地址了,如果作者发现请联系我,我加上引用地址。

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

标签:包含   url   pytho   from   数据   build   screen   mem   turn   

原文地址:http://www.cnblogs.com/hoods/p/6413330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!