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


在使用Zabbix的过程中,我们通常会建立一些需要的Screen图形报表来汇总需要监控的Graph。
而下面的两个脚本,则是通过从Zabbix数据库中获取所有的Screen图形参数,提供Zabbix的WEB接口将所有图形保存到本地,然后通过脚本以Email形式发送过来,作为每天的自动报表。

$ sudo mkdir -p /data/script
$ sudo mkdir -p /data/graph

$ sudo vim /data/scripts/save-graph.pl

#!/usr/bin/perl
use File::Path;
use DBI;

my $path = '/data/graph';
if(-e $path) { rmtree($path); }
mkdir($path);

my $stime = `date +%Y%m%d`; chop($stime); $stime .= '1000';
if( length($stime) != 12 ) { print "Error get date"; exit; }

my $period = 86400;    # 24 hours

my $login = 'admin';   # Zabbix Web User
my $pass = 'password'; # Zabbix Web User Password, must be URL Encoded

my $cook = "/tmp/cookie";
my $dsn = 'DBI:mysql:zabbix:localhost'; # Connect MySQL DB "zabbix" on localhost
my $db_user_name = 'zabbix'; # MySQL DB user
my $db_password = 'dbpassword'; # MySQL DB user password

my $dbh = DBI->connect($dsn, $db_user_name, $db_password);
my $sth = $dbh->prepare(qq{select a.name,a.hsize,a.vsize, b.resourceid, b.width, b.height,b.x,b.y from screens a,screens_items as b where a.screenid=b.screenid and a.templateid<=>NULL order by a.name});
$sth->execute();
my %screens;

# Get all graphs by using curl
while (my ($name,$hsize,$vsize, $id,$width,$height,$x,$y) = $sth->fetchrow_array())
{
    if(length($id) > 2){
        #print "$id => $ids\n";
        my $p = "$path/$name.$hsize.$vsize.$y.$x.$id.png";
        my $strcomm  = `curl  -c $cook -b $cook -d "request=&name=$login&password=$pass&autologin=1&enter=Sign+in"  localhost/zabbix/index.php`;
        $strcomm  = `curl  -b $cook -F  "graphid=$id" -F "period=$period" -F "stime=$stime" -F "width=$width" -F "height=$height" localhost/zabbix/chart2.php > $p`;
    }
}

exit ;


$ sudo vim email-pic.py

#! /usr/bin/env python

import os
import smtplib

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

def _sendmail(smtp_server,port,account,password,str_from,list_to,msg):
    smtp = smtplib.SMTP(smtp_server,port)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(account, password)
    smtp.sendmail(str_from, list_to,msg)
    smtp.close()

def _get_pictures(image_dir):
    pictures = []
    for f in os.listdir(image_dir):
        pictures.append(f)
    return pictures

def _create_msg(screen_name,screens,image_dir,str_from,list_to):
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Zabbix Screen Report: %s' % screen_name
    msgRoot['From'] = str_from
    msgRoot['To'] = ",".join(list_to)
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)
    contents = ""
    contents += "<h1>Screen %s</h1><br>" % screen_name
    _,hsize,vsize,_,_,_,_,= tuple(screens[0].split('.'))
    contents +="<table>"
    screens = sorted(screens)
    y= -1
    for f in screens:
        items = f.split('.')
        _,_,_,image_y,image_x,image_id,_ = tuple(items)
        image_name = "image-%s-%s" % (screen_name, image_id)
        fp = open('%s/%s' % (image_dir,f), 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', "<%s>" % image_name)
        msgRoot.attach(msgImage)
        if y != image_y:
            if y!= -1:
                contents +="</tr>"
            y = image_y
            contents +="<tr>"
        contents +="<td><img src='cid:%s'></td>" % image_name
    contents += "</table>"
    msgText = MIMEText(contents, 'html')
    msgAlternative.attach(msgText)
    msgRoot.attach(msgAlternative)
    return msgRoot

# Create the root message and fill in the from, to, and subject headers
def main(str_from,list_to,image_dir):
    pictures = _get_pictures(image_dir)
    for screen_name in list(set([x.split('.')[0] for x in pictures ])):
        screens = [x for x in pictures if x.startswith(str(screen_name) + '.') ]
        msgRoot = _create_msg(screen_name,screens,image_dir,str_from,list_to)
        _sendmail('smtp.example.com',25,'username','password',str_from,list_to,msgRoot.as_string())

if __name__ == '__main__':
   str_from = 'username@example.com'
   list_to = [
                "jack@example.com", "tom@example.com", "jim@example.com"
             ]
   image_dir = '/data/graph'
   main(str_from,list_to,image_dir)

接着,将这两个脚本加入到crontab中定时执行。

$ sudo crontab -e
30 23 * * * /data/script/save-graph.pl
55 23 * * * /data/script/email-pic.py

这样,就可以收到对应的Zabbix图形邮件报表了,如下图所示:

, ,

  1. #1 by hengfg on 2013/01/22 - 20:12

    这个能不能按周显示啊?

    • #2 by mcsrainbow on 2013/01/22 - 20:24

      可以啊,my $period = 86400; 这里就是用来定义时间的,以秒为单位。

      • #3 by han on 2013/07/15 - 13:32

        我看你这个脚本好像是统计脚本执行时间之前的24个小时的,怎么改成统计过去一天0点-24点的数据,请指导一下,我脚本不太好

      • #4 by anders on 2013/09/22 - 16:36

        为啥my $period低于3600就显示不了?
        我就需要显示几秒的图形,可以吗?

      • #5 by tom on 2014/04/25 - 10:47

        你这需要安装到python2.7中么 python2.6无法使用呢

  2. #6 by hengfg on 2013/01/23 - 14:33

    你好,我执行python时出错,麻烦帮助看一下。python2.6\2.7版本都试过

    Traceback (most recent call last):
    File "./email-pic.py", line 80, in
    main(str_from,list_to,image_dir)
    File "./email-pic.py", line 71, in main
    msgRoot = _create_msg(screen_name,screens,image_dir,str_from,list_to)
    File "./email-pic.py", line 41, in _create_msg
    _,hsize,vsize,_,_,_,_,= tuple(screens[0].split('.'))
    IndexError: list index out of range

    • #7 by mcsrainbow on 2013/01/23 - 17:28

      必须和上面的脚本和步骤配合使用,完成的任务其实就是,创建目录,利用Zabbix接口生成好好图片,然后通过邮件发送。

      • #8 by young.liu on 2014/02/13 - 09:55

        Traceback (most recent call last):
        File "./email-pic.py", line 79, in
        main(str_from,list_to,image_dir)
        File "./email-pic.py", line 70, in main
        msgRoot = _create_msg(screen_name,screens,image_dir,str_from,list_to)
        File "./email-pic.py", line 40, in _create_msg
        _,hsize,vsize,_,_,_,_, = tuple (screens[0].split('.'))
        IndexError: list index out of range

        我也是类似的报错 这个和第一脚本配合起来 只能发出一个screen 我定义了好多screen

  3. #9 by lihai on 2013/07/19 - 11:42

    谢谢 ,我在新版ZABBIX里应用了,对你的代码做了些改动。

    • #10 by hellomwb on 2014/11/13 - 11:15

      您好,麻烦能说明下修改了什么吗?我用的版本似乎有问题。谢谢

  4. #11 by kangshao on 2013/10/29 - 15:29

    你好,为什么我测试的时候每次的开始时间都是系统当前时间,而不是设置的stime。

  5. #12 by youyan on 2013/12/25 - 12:44

    你好,qq邮箱收到的图片都只是重复第一张,该怎么修改呢?求助啊,其他邮箱正常

  6. #13 by denny on 2014/06/10 - 02:21

    建议,在文章的开头用两三句话介绍一下,zabbix哪张table哪一处存了Screen的图表。

    把数据结构和原理先讲清楚,再讲细节会好些。而且,代码不一定那么好复用。 比如,你这里用perl, 别人可能只会python或bash.

  7. #14 by sam on 2014/07/22 - 10:31

    您好,

    能否产生PDF格式的报告格式呢?

    非常感谢!

  8. #15 by huam on 2015/11/05 - 10:02

    这脚本好,zabbix2.4.6还能用,赞

(will not be published)
*