脚本处理逻辑分析:
通过zabbix传递给脚本的message参数,筛选出报警信息的itemid;
通过itemid获取到图片并保存;
将报警信息和图片组装成html;
发送邮件。
后续脚本里面的处理细节还会在进一步分析,将脚本中涉及到的代码行进行注释分析
#!/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
参考:微信公众号: 数睿技术
- zabbix 告警实践分享 一键实现zabbix 电话、邮件、微信告警
众所周知Zabbix 是一款用来监控IT基础设施的监控套件,同时也具有很多方便运维人员使用的优秀功能,如:支持多条件告警,支持多种告警方式,支持多组模板.支持模板继承,因此在众多的开源运维监控软件中独 ...
- zabbix 告警小试
zabbix 告警小试 1. 实验内容简述 本次实验,旨在通过zabbix监控,实现对告警信息的实时通知,主要用到了zabbix中的item.trigger.action.user.user grou ...
- 通过微信服务号推送Zabbix告警
近期看到一篇通过微信实现Zabbix告警的文章,但实践时发现,无法成功发送消息. 分析原因,应该是微信公众平台加强了登录验证,在登录时会需要管理员进行扫描二维码操作才能成功登陆后台: 而之前文章中的A ...
- 一个简单好用的zabbix告警信息发送工具
之前使用邮件和短信发送zabbix告警信息,但告警信息无法实时查看或者无法发送,故障无法及时通知运维人员. 后来使用第三方微信接口发送信息,愉快地用了一年多,突然收费了. zabbix告警一直是我的痛 ...
- [置顶]
个人微信号发送zabbix告警信息
之前使用邮件和短信发送zabbix告警信息,但告警信息无法实时查看或者无法发送,故障无法及时通知运维人员. 后来使用第三方微信接口发送信息,愉快地用了一年多,突然收费了. zabbix告警一直是我的痛 ...
- [置顶]
一个简单好用的zabbix告警信息发送工具
之前使用邮件和短信发送zabbix告警信息,但告警信息无法实时查看或者无法发送,故障无法及时通知运维人员. 后来使用第三方微信接口发送信息,愉快地用了一年多,突然收费了. zabbix告警一直是我的痛 ...
- zabbix告警邮件美化
为了更好的用户体验,我们需要尽量美化我们的输出内容,尽量做到整齐划一,让人看了会有很舒服的感觉, 这个好像和苹果的产品一样,给人一种美感让人感觉非常享受. 一般我们的zabbix告警邮件就是纯文字,建 ...
- CMDB机柜平台结合zabbix告警展示
前段时间看了刘天斯老师的机柜展示平台,非常绚丽,而且有大屏显示的话也是能够体现运维价值的.刚好最近自己也在协助朋友做一个开源的CMDB平台,这里就说下我们CMDB平台的一些数据: 开源项目地址:Git ...
- Java发送邮件时标题和发件人乱码
最近碰到一个问题,Java发送邮件时,查看邮箱结果,发件人及邮件标题正文全部乱码 通过翻阅资料,原因及解决方法如下: // Set Subject: 头字段 message.setSubject(Mi ...
随机推荐
- Linux operating system basic knowleadge
1.Linux目录系统结构 It makes sense to explore the Linux filesystem from a terminal window. In fact, that ...
- npm ERR! code ENOENT
npm ERR! path F:\VsCodeWorkspace\labWeb\front\LabWebAdminFrontEnd\node_modules\core-jsnpm ERR! code ...
- Linux -- nginx
一. 网络服务 web服务器和web框架的关系 web服务器(nginx):接收HTTP请求(例如www.baidu.com)并返回数据 web框架(django,flask):开发web应用程序,处 ...
- Swift 之Carthage
1. 安装 $ brew update //更新brew $ brew install carthage //下载carthage $ carthage version ...
- Django_RBAC_demo2 升级版权限控制组件
RBAC 升级版 预期要求 前端在无权限时不在提供操作标签 更改部分硬编码 实现更加精准的权限控制 未改动前的版本 在这里 ⬇ Django_rbac_demo 权限控制组件框架模型 具体更改 数据库 ...
- Magento CURD
创建数据库表 创建模型-CRUD模型Model是MVC架构的一条巨大路径.在Magento 2 CRUD中,模型具有许多不同的功能,例如管理数据,安装或升级模块.在本教程中,我只讨论数据管理CRUD. ...
- 「洛谷1884」「USACO12FEB」过度种植【离散化扫描线】
题目链接 [洛谷传送门] 题解 矩阵面积的并模板.(请求洛谷加为模板题) 很明显是要离散化的. 我们将矩阵与\(x\)轴平行的两个线段取出来.并且将这两个端点的\(x1\)和\(x2\)进行离散化. ...
- Help Me Escape ZOJ - 3640
Background If thou doest well, shalt thou not be accepted? and if thou doest not well, sin lieth ...
- RQY大佬一晚报告总结
首先基础真的很重要.今天所有学的东西,都是为明天做铺垫,(这样看好像每天都是基础)基础牢了,学东西也就一看就会的感觉吧. 其次,自学能力很重要,投入很重要.大佬说他自己也不是看一遍书就懂的,而是反复看 ...
- Window下Eclipse+Tomcat远程调试
需求: 项目在开发环境跑得好好的,但是当发布到服务器上时,却出现了一些意外的问题.服务器上不可能给你装IDE调试工具啊,又没有很好的日志帮助下,这时候就用到了JVM的Java Platfo ...