Python获取zabbix告警性能监控图并邮件发送

4,817 views次阅读
6条评论

思路

  • 通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
  • 通过获取的itemid,在数据库中查找对应的grpahid;
  • 拉取对应graphid的图片并保存;
  • 将报警信息和图片组装成html;
  • 发送邮件

 脚本

获取itemid

从zabbix传来的第三个参数(message)中,通过re过滤出itemid

def get_itemid(self):
    # 获取itemid
    pattern = re.compile('ITEM.*?:(\d+)',re.S)
    itemid = re.findall(pattern,sys.argv[3])
    itemid = str(itemid).lstrip('[\'').rstrip('\']')
    return itemid

获取graphid

将上一步得到的itemid传入该函数,并通过pymysql连接zabbix-server所在的数据库进行查询,得到graphid

def get_graphid(self):
    itemid = self.get_itemid()
    conn = pymysql.connect(host=self.host, user=self.username, password=self.password, port=3306, db='zabbix')
    cur = conn.cursor()
    cur.execute("SELECT graphid  FROM `graphs_items` WHERE `itemid`=%s;" % itemid)
    result = cur.fetchone()
    cur.close()
    conn.close()
    graphid = re.findall(r'\d+', str(result))
    graphid = str(graphid).lstrip('[\'').rstrip('\']')
    print(graphid)
    return graphid

获取性能监控图片url并保存至文件

def get_img(self):
    time = self.time
    graph_id = self.get_graphid()
    img_url = 'http://' + str(self.host) +'/zabbix/' + 'chart2.php?graphid=%s&period=%s&isNow=1&profileIdx=web.graphs&profileIdx2=797&width=1000' %(graph_id,time)
    print(img_url)
    try:
        response = requests.get(img_url,headers = self.headers)
        if response.status_code == 200:
            return response.content
        else:
             return None
    except Exception as e:
        print(e)
def save_img(self):
    content = self.get_img()
    tm = datetime.datetime.now()
    time = tm.strftime("%Y-%m-%d-%H%M%S")
    string = str(self.savedir) + '/' + 'zabbix_' + str(time) + '.jpg'
    fp = open(string, 'wb')
    fp.write(content)
    fp.close()
    return string

发送邮件

def sendmail(self,toemail,subject):
    imgname = self.save_img()
    html_text = self.convert_to_html(sys.argv[3])
    smtp_host = 'smtp.qq.com'
    from_email = 'zabbix@cloudcared.cn'
    passwd = 'stlq'
    msg = MIMEMultipart('related')
    fp = open(imgname, 'rb')
    image = MIMEImage(fp.read())
    fp.close()
    image.add_header('Content-ID', '<image1>')
    msg.attach(image)
    html = """
         <html>
          <body>
        """
    html += html_text
    html += '<img src="cid:image1"></br>'
    html += """
          </body>
        </html>
        """
    html = MIMEText(html, 'html', 'gb2312')
    msg.attach(html)
    msg['Subject'] = subject
    msg['From'] = from_email
    smtp_server = smtplib.SMTP_SSL()
    smtp_server.connect(smtp_host, '465')
    smtp_server.login(from_email, passwd)
    smtp_server.sendmail(from_email, toemail, msg.as_string())
    smtp_server.quit()
    print(imgname)

最终代码

# -*- coding:utf-8 -*-
#!/usr/local/python3/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import pymysql
import re,sys,os,requests,datetime,time
class zabbix_img(object):
    def __init__(self,url,host,username,password,time):
        self.host = host
        # 指定zabbix获取图片的地址
        self.chart2_url = 'http://172.20.2.11/zabbix/chart2.php'
        # zabbix登录账户
        self.zabbix_user = 'Admin'
        # zabbix登录密码
        self.zabbix_pwd = 'zabbix'
        self.username = username
        self.password = password
        self.url = url
        self.time = time
        self.alerttime = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
    def get_itemid(self):
        # 获取Itemid
        pattern = re.compile('ITEM.*?(\d+)',re.S)
        itemid = re.findall(pattern,sys.argv[3])
        itemid = str(itemid).lstrip('[\'').rstrip('\']')
        return itemid
    def get_graphid(self):
        itemid = self.get_itemid()
        conn = pymysql.connect(host=self.host, user=self.username, password=self.password, port=3306, db='zabbix')
        cur = conn.cursor()
        cur.execute("SELECT graphid  FROM `graphs_items` WHERE `itemid`=%s;" % itemid)
        result = cur.fetchone()
        cur.close()
        conn.close()
        graphid = re.findall(r'\d+', str(result))
        graphid = str(graphid).lstrip('[\'').rstrip('\']')
        print(graphid)
        return graphid


    def get_img(self):
        graphid = self.get_graphid()
        #  拉取图片
        os.system('curl -L -c /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -d "reauest=&name=%s&password=%s&autologin=1&enter=Sign+in" %s' % (self.zabbix_user, self.zabbix_pwd, self.url))
        os.system('curl -c /usr/lib/zabbix/alertscripts/cookie.txt -b /usr/lib/zabbix/alertscripts/cookie.txt --user-agent Mozilla/4.0 -F "graphid=%s" -F "period=%s" -F "width=900" %s > /usr/lib/zabbix/img/zabbix_%s.png' % (graphid, self.time, self.chart2_url, str(self.alerttime)))
        img_name = '/usr/lib/zabbix/img/' + 'zabbix_' + str(self.alerttime) + '.png'
        print(img_name)
        return img_name
    def convert_to_html(self,text):
        d = text.splitlines()
        html_text = ''
        for i in d:
            i = '' + i + '</br>'
            html_text += i + '\n'
        return html_text
    def sendmail(self,toemail,subject):
        imgname = self.get_img()
        html_text = self.convert_to_html(sys.argv[3])
        smtp_host = 'smtp.qq.com'
        from_email = 'zabbix@cloudcared.cn'
        passwd = 'stlqpedmjshrcahb'
        msg = MIMEMultipart('related')
        fp = open(imgname, 'rb')
        image = MIMEImage(fp.read())
        fp.close()
        image.add_header('Content-ID', '<image1>')
        msg.attach(image)
        html = """
             <html>
              <body>
            """
        html += html_text
        html += '<img src="cid:image1"></br>'
        html += """
              </body>
            </html>
            """
        html = MIMEText(html, 'html', 'gb2312')
        msg.attach(html)
        msg['Subject'] = subject
        msg['From'] = from_email
        smtp_server = smtplib.SMTP_SSL()
        smtp_server.connect(smtp_host, '465')
        smtp_server.login(from_email, passwd)
        smtp_server.sendmail(from_email, toemail, msg.as_string())
        smtp_server.quit()
        print(imgname)
def main():
    url = 'http://172.20.2.11/zabbix/index.php'
    host = '172.20.2.11'
    username = 'zabbix'
    password = 'zabbix'
    time = '600'
    to = sys.argv[1]
    subject = sys.argv[2]
    zabbixOper = zabbix_img(url,host,username,password,time)
    zabbixOper.get_img()
    zabbixOper.sendmail(to,subject)

if __name__ == '__main__':
    main()

测试

Python获取zabbix告警性能监控图并邮件发送

Python获取zabbix告警性能监控图并邮件发送

Honest1y
版权声明:本站原创文章,由Honest1y于2018年08月30日发表,共计7680字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(6条评论)
头像
Waiting for you 评论达人LV.1
2019-02-26 11:45:49 回复

你好,我想请问这个第三个参数改怎么获取,我这边一直获取不到就是拉取图片,报错说我的检索超出范围

    Wangxiao
    Wangxiao 博主
    2019-02-26 13:01:19 回复

    @Waiting for you 第三个参数在设置告警模板的时候设置,告警消息的消息内容设置:
    告警主机:{HOST.NAME}
    阈值名称:{TRIGGER.NAME}
    ITEM ID :{ITEM.ID}
    告警时间:{EVENT.DATE} {EVENT.TIME}

      头像
      张伟大 评论达人LV.1
      2019-03-05 14:35:45 回复

      @Wangxiao 你好在吗?这个到底要怎么搞 能加下我qq1141912008,我这边实在搞不定,没看懂你这个argv啥啥意思

        Wangxiao
        Wangxiao 博主
        2019-03-05 14:41:49 回复

        @张伟大 首页右边栏,关于本站地下有QQ可以联系

      头像
      Waiting for you 评论达人LV.1
      2019-03-05 14:40:00 回复

      @Wangxiao 博主可以加下你qq吗。我的是1028334703