Zabbix告警发送邮件时附带性能图
脚本处理逻辑分析:[*] 通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
[*] 通过itemid获取到图片并保存;
[*] 将报警信息和图片组装成html;
[*] 发送邮件。
后续脚本里面的处理细节还会在进一步分析,将脚本中涉及到的代码行进行注释分析
#!/usr/bin/env python
#coding=utf-8from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.image import MIMEImageimport MySQLdb,smtplib,sys,os,time,reimport graphimport loggingimport logging.configimport logging.handlersimport tracebackimport 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.phpmysql_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> 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" : 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) 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.argvsubject=sys.argvsubject=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) 执行结果图片:
https://images2018.cnblogs.com/blog/1207806/201711/1207806-20171129110735690-137451905.png
参考连接:http://www.bubuko.com/infodetail-1678696.html
参考:微信公众号: 数睿技术 有没有图文安装教程 ,新人正在入门 这个很不错
页:
[1]