zabbix可以说是现在最受欢迎的开源监控软件了,满足大多数监控的需求。通常管理人员会自定义聚合图形,只要登录zabbix查看就能大概了解服务器的情况。为了偷懒,有什么方法可以实现每天自动发送这些报表吗?或者发送给领导看。Google了一番终于找到了我要的答案···
特别提醒
这里的大部都是参考自这里 http://ant595.blog.51cto.com/5074217/1432623
在阅读这里之前,建议先看这篇文章
代码
cat zabbix_send_report.py1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115#! /usr/bin/env python
#coding=utf-8
# Vincent927
import time,os
import urllib
import urllib2
import cookielib
import pymysql as MySQLdb
import smtplib
from email.mime.text import MIMEText
 
screens = ["Memory","Processor Load"]
save_graph_path = "/var/www/html/reports/%s"%time.strftime("%Y-%m-%d")
if not os.path.exists(save_graph_path):
    os.makedirs(save_graph_path)
# zabbix host
zabbix_host = "zabbix.xxx.com"
# zabbix login username
username = "xxx"
# zabbix login password
password = "xxx"
# graph width
width = 600
# graph height
height = 100
# graph Time period, s
period = 86400
# zabbix DB
dbhost = "xx.xx.xx.xx"
dbport = 3306
dbuser = "xxx"
dbpasswd = "xxx"
dbname = "xxx"
# mail
to_list = ["xxx@qq.com","xxx@163.com"]
smtp_server = "smtp.xx.com"
mail_user = "xxx"
mail_pass = "xxx"
domain  = "qq.com"
 
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):
    screenid_list = []
    global html
    html = ''
    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' order by resourceid"%(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)
                        html += '<img width="600" height="250" src="http://%s/%s/%s/%s.%s.png">'%(zabbix_host,save_graph_path.split("/")[len(save_graph_path.split("/"))-2],save_graph_path.split("/")[len(save_graph_path.split("/"))-1],screenid,graphid)
                        f = open(filename,"wb")
                        f.write(data)
                        f.close()
 
 
def send_mail(username,password,smtp_server,to_list,sub,content):
    print to_list
    me = "运维"+"<"+username+"@"+domain +">"
    msg = MIMEText(content,_subtype="html",_charset="utf8")
    msg["Subject"] = sub
    msg["From"] = me
    msg["To"] = ";".join(to_list)
    try:
        server = smtplib.SMTP()
        server.connect(smtp_server)
        server.login(username,password)
        server.sendmail(me,to_list,msg.as_string())
        server.close()
        print "send mail Ok!"
    except Exception, e:
        print e
 
if __name__ == '__main__':
    for screen in screens:
	print screen
        get_graph(zabbix_host,username,password,screen,width,height,period,save_graph_path)
	title="生产环境服务器日报-%s"%screen
	print title
        send_mail(mail_user,mail_pass,smtp_server,to_list,title,html)
以上代码相较于参考的代码做了如下改进:
- screens = [“Memory”,”Processor Load”] 之前老的代码如果screens有多个,只会把最后的screen发出来,也就是只会发送Processor Load。这里通过把不同的screen发送不同的邮件,修复了这个Bug,同样邮件看起来也更美观。
- 优化了发送邮件的主题,根据screen名字的不同,邮件主题也与之对应。
- 由于我是在centos7上面运行的,默认的python版本是2.7.5,pip install mysqldb 找不到这个包,这里我们改用pymysql这个包。并设置别名为MySQLdb import pymysql as MySQLdb减少对代码的修改。Centos6可以不用修改import MySQLdb
- 亲测兼容Zabbix3
注意
这里记录一下几个容易出错的地方
- zabbix server 一定是要能够公网访问到的,不然邮件是引用不到保存在服务器上的图片
- save_graph_path = "/var/www/html/reports/%s"%time.strftime("%Y-%m-%d")图片的的保存目录一定要和zabbix的根目录保持一致,不然邮件是调用不到这些图片的
- screens = ["Memory","Processor Load"]这里是填screen的名称,而不是screen的ID。如下图所示 
效果
我们看下最后的效果图如下

 
          