领导有个需求,希望每天邮件发出当天服务器的监控状态,开始是每天下午快下班的时候打开zabbix截图,每天都这样实在是累,于是写了一段脚本实现自动抓取图片,并组装成html,通过定时邮件发送,实现日报自动化。"zabbix 邮件发送监控图片"
以下则是我通过python的脚本获取zabbix图片的实现过程。
#_*_coding:utf-8_*_ import sys import datetime import cookielib, urllib2,urllib 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 def GetGraph(self,url,values,image_dir): key=values.keys() if "graphid" 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["graphid"]) f=open(imagename,‘wb‘) f.write(image) #此url是获取图片是的,请注意饼图的URL 和此URL不一样,请仔细观察! gr_url="http://zabbix.XXXX.com/chart2.php" #登陆URL indexURL="http://zabbix.XXX.com/index.php" username="xxxx" password="xxxx" #用于图片存放的目录 image_dir="/tmp" #图片的参数,该字典至少传入graphid。 values={"graphid":"582","period":86400,"stime":20160101000000,"width":800,"height":200} b=ZabbixGraph(indexURL,username,password) b.GetGraph(gr_url,values,image_dir)
通过以上获取的图片,在组装html,可实现自动化日报发送。
本文出自 “运维笔记” 博客,请务必保留此出处http://sandy521.blog.51cto.com/5728588/1736876
原文:http://sandy521.blog.51cto.com/5728588/1736876