Zabbix告警發送郵件時附帶性能圖


腳本處理邏輯分析:

  1. 通過zabbix傳遞給腳本的message參數,篩選出報警信息的itemid;

  2. 通過itemid獲取到圖片並保存;

  3. 將報警信息和圖片組裝成html;

  4. 發送郵件。

后續腳本里面的處理細節還會在進一步分析,將腳本中涉及到的代碼行進行注釋分析

#!/usr/bin/env python

#coding=utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import MySQLdb,smtplib,sys,os,time,re
import graph
import logging
import logging.config
import logging.handlers
import traceback
import requests
#日志輸出配置格式
logger = logging.getLogger("root")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("[%(asctime)s %(filename)s:%(lineno)s - %(funcName)15s()] %(message)s")
 
#日志輸出位置,到指定/hskj/logs/Data_sheet.log這個文件,從系統規划上,日志統一放置到這個地方
handler = logging.handlers.RotatingFileHandler("/hskj/logs/altermail_img.log")
handler.setFormatter(formatter)
logger.addHandler(handler)
user='USER'
#zabbix用戶名
password='PASSWORD'
#zabbix密碼
url='http://IP/zabbix/'
#zabbix首頁
period='3600'
chart2_url='http://IP/chart2.php'
#zabbix獲取圖片url http://IP/chart2.php
mysql_host='localhost'
mysql_user='root'
mysql_pass='MYSQLPASSWD'
mysql_db='zabbix'
#zabbix數據庫相關信息
graph_path='/usr/local/zabbix/alertscripts/'
#圖片保存路徑
 
def get_itemid():
    #獲取itemid
    a=re.findall(r"ITEM ID:\d+",sys.argv[3])
    i=str(a)
    itemid=re.findall(r"\d+",i)
    logger.info(itemid)
    return str(itemid).lstrip('[\'').rstrip('\']')
    
def get_graphid(itemid):
    #獲取graphid
    conn =MySQLdb.connect(host=mysql_host,user=mysql_user,passwd=mysql_pass,db=mysql_db,connect_timeout=20)
    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))
    logger.info(graphid)
    
    return str(graphid).lstrip('[\'').rstrip('\']')
#get grafa#
def get_graph(itemID,pName=None):
    myRequests = requests.Session()
    HOST='IP'
    try:
        """
        獲取性能圖,首先需要登錄
        通過分析,可以直接Post/Get方式登錄
        """
        loginUrl = "http://%s/zabbix/index.php" % HOST
        loginHeaders={            
        "Host":HOST,            
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        }
        
        # 構建登錄所需的信息
        playLoad = {            
        "name":"USER",
        "password":'PASSWORD',  
        "autologin":"1",            
        "enter":"Sign in",
        }
        
        # 請求登錄 
        res = myRequests.post(loginUrl,headers=loginHeaders,data=playLoad)
        """
        登入狀態后,在POST數據中加入itemid
        """
        testUrl = "http://%s/zabbix/chart.php" % HOST
        testUrlplayLoad = {            
            "period" :"10800",            
            "itemids[0]" : itemID,            
            "type" : "0",            
            "profileIdx" : "web.item.graph",            
            "width" : "700",
        }
        testGraph = myRequests.get(url=testUrl,params=testUrlplayLoad)
        
        # 返回圖片源碼,直接保存到本地
        IMAGEPATH = os.path.join('/usr/local/zabbix/alertscripts/imges/', pName)
        f = open(IMAGEPATH,'wb')
        f.write(testGraph.content)
        f.close()
        pName = '/usr/local/zabbix/alertscripts/imges/' + pName
        return pName    
        
    except Exception as e:        
        print e        
        return False
 
def text_transfe_html(text):
    #將message轉換為html
    d=text.splitlines()
    html_text=''
    for i in d:
        i='' + i + '</br>'
        html_text+=i + '\n'
    return html_text
    
def send_mail(to_email,subject,picture_name):
    #發送郵件
    graph_name=get_graph(itemid,picture_name)
    html_text=text_transfe_html(sys.argv[3])
    smtp_host = 'MAIL_SERVER'
    from_email = 'FROM'
    #郵箱賬戶
    passwd = 'PASSWD'
    #郵箱密碼
    msg=MIMEMultipart('related')
    fp=open(graph_name,'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','utf8')
    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,to_email,msg.as_string())
    smtp_server.quit()
     
if __name__ == '__main__':
  time_tag=time.strftime("%Y%m%d%H%M%S", time.localtime())
  to=sys.argv[1]
  subject=sys.argv[2]
  subject=subject.decode('utf-8')
  itemid=get_itemid()
  #graphid=get_graphid(itemid)
  picture_name=time_tag + ".png"
  graph_name=get_graph(itemid,picture_name)
  send_mail(to,subject,picture_name)

執行結果圖片: 

 

參考連接:http://www.bubuko.com/infodetail-1678696.html 

參考:微信公眾號: 數睿技術

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM