Zabbix报警脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Zabbix报警脚本相关的知识,希望对你有一定的参考价值。

最近上线zabbix由于自带的报警不够直观,领导要求增加监控项的图片,网上找了很多相关的脚本,多少都有些问题,于是自己写了一个,可能不够完善异常判断没加很多,不过线上跑了一段时间没发现啥问题,贴代码共大家参考(其中url及账户密码请自行修改)

#!/usr/bin/env python
# encoding: utf8
import sys, os
import datetime
import cookielib, urllib2, urllib, re
import smtplib, mimetypes, time, traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage

class ZabbixGraph(object):
    def __init__(self, url, name, password):
        self.url = url
        self.name = name
        self.password = password
        # 初始化的时候生成cookies
        cookiejar = cookielib.CookieJar()
        urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
        values = {"name": self.name, password: self.password, autologin: 1, "enter": Sign in}
        data = urllib.urlencode(values)
        request = urllib2.Request(url, data)
        try:
            urlOpener.open(request, timeout=10)
            self.urlOpener = urlOpener
        except urllib2.HTTPError, e:
            print e

    # 爬取zabbix报警图片,并保存到本地
    def GetGraph(self, url, values, image_dir):
        key = values.keys()
        if "itemids" not in key:
            print u"请确认是否输入graphid"
            sys.exit(1)
        # 以下if 是给定默认值
        if "period" not in key:
            # 默认获取一天的数据,单位为秒
            values["period"] = 86400
        if "stime" not in key:
            # 默认为当前时间开始
            values["stime"] = datetime.datetime.now().strftime(%Y%m%d%H%M%S)
        if "width" not in key:
            values["width"] = 800
        if "height" not in key:
            values["height"] = 200

        data = urllib.urlencode(values)
        request = urllib2.Request(url, data)
        url = self.urlOpener.open(request)
        image = url.read()
        imagename = "%s/%s.png" % (image_dir, values["itemids"])
        f = open(imagename, wb)
        f.write(image)

    # 传入zabbix报警内容,通过正则过滤itemid
    def getvalue(self, string):
        r = re.compile("^ITEMID:[0-9]*", re.M)
        for i in string:
            d = r.findall(string)
        str1 = d[0]
        arrstr = str.split("\\xa3\\xba")
        arrstr = str1.split(":")
        result = arrstr[1]
        return result

    # 格式化报警内容
    def printmlinestr(self,mlinestr):
        d = mlinestr.splitlines()
        res = ""
        for i in d:
            i = "<br>" + i + "</br>"
            res += i + \\n
        return res

    # 发送邮件
    def SendMail(self,receivers, subject, data, picpath, itemid):
        msg = MIMEMultipart()
        msg[From] = "[email protected]"
        receives = receivers
        msg[To] = receivers
        msg[Subject] = subject
        body = self.printmlinestr(data)
        file1 = picpath
        image = MIMEImage(open(file1, rb).read())
        image.add_header(Content-ID, <image1>)
        msg.attach(image)
        html = """ 
        <html> 
          <body>
        """
        html += body
        html += "<br><img src=cid:image1></br>"

        html += """     
            </body> 
        </html>
        """
        htm = MIMEText(html, html, gb2312)
        msg.attach(htm)
        server = smtplib.SMTP()
        server.connect(‘你的邮箱)
        server.login(用户名, 密码)
        server.sendmail(msg[From], receives, msg.as_string())
        server.quit()

#此url是获取图片是的,请注意饼图的URL 和此URL不一样,请仔细观察!
gr_url="http://x.x.x.x/zabbix/chart.php"
#登陆URL
indexURL="http://x.x.x.x/zabbix/index.php"
username="username"
password="password"
#用于图片存放的目录
image_dir="/tmp/"
#图片的参数,该字典至少传入graphid。
b=ZabbixGraph(indexURL,username,password)
rex = b.getvalue(sys.argv[3])
values={"itemids":"%s" %(rex),"period":86400,"stime":20160101000000,"width":800,"height":200 }
b.GetGraph(gr_url,values,image_dir)
picpath = %s%s.png %(image_dir,rex)
# 将zabbix传入的信息从utf8转为gbk
title = sys.argv[2].decode(utf-8).encode(gbk)
msg = sys.argv[3].decode(utf-8).encode(gbk)
# 发送邮件
b.SendMail(sys.argv[1], title, msg,picpath,rex)
# 删除本地无用的png图片
os.remove(picpath)

 

效果图:

技术分享图片

 

以上是关于Zabbix报警脚本的主要内容,如果未能解决你的问题,请参考以下文章

zabbix邮件报警脚本

zabbix报警(向消息中心发送报警信息)

Zabbix 3.2 短信报警配置

通过脚本发送zabbix邮件报警

Zabbix3.0.2使用外部python脚本实现邮件报警

zabbix邮件报警及自定义脚本实战