首页 > 代码库 > [ python3 ] 基于zabbix 自动抓取每天监控数据

[ python3 ] 基于zabbix 自动抓取每天监控数据

  通过python登录到zabbix直接抓取每天的数据的图片趋势图,并制作成静态index.html给与展示并发送提示邮件。

操作系统:Centos6.7

python版本:python3.5

 

#!/usr/local/python/bin/python3.5
import sys, os, shutil
import os.path
import datetime
import http.cookiejar
import urllib.request
import urllib.error
import urllib.parse
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
class ZabbixGraph(object):
    def __init__(self, url, name, password):
        self.url = url
        self.name = name
        self.password = password
        cookiejar = http.cookiejar.CookieJar()
        urlOpener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
        values = {"name":self.name,password:self.password,autologin:1,"enter":Sign in}
        data = urllib.parse.urlencode(values).encode(encoding=UTF8)
        request = urllib.request.Request(url, data)
        try:
            urlOpener.open(request, timeout=10)
            self.urlOpener = urlOpener
        except urllib.error.HTTPError as e:
            print(e)

    def getgraph(self, url, values, image_dir):
        key = values.keys()
        if graphid not in key:
            # print(‘请确认是否输入graphid‘)
            sys.exit(1)
        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.parse.urlencode(values).encode(encoding=UTF8)
        request = urllib.request.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)
def yesterday():
    now_time = datetime.datetime.now()
    yes_time = now_time + datetime.timedelta(days=-1)
    yes_time_nyr = yes_time.strftime(%Y%m%d)
    yes_time_nyr1 = yes_time.strftime(%Y-%m-%d)
    return yes_time_nyr, yes_time_nyr1

def email():
    sender = 发送者
    receiver = [接收者1, 接收者2, 接收者3]
    subject = 每日重点监控对象
    smtpserver = smtp.126.com
    username = 发送者邮箱
    password = smtp密码
    msgRoot = MIMEMultipart(related)
    text = yesterday1+ 重点监控数据报告已生成。\n请访问:http://xxx/+yesterday+/index.html
    msg = MIMEText(text, plain, utf-8)  # 中文需参数‘utf-8‘,单字节字符不需要
    msg[Subject] = Header(subject, utf-8)
    msg[From] = Robot<xxx>
    msg[To] = 接收者别名
    smtp = smtplib.SMTP()
    smtp.connect(smtp.126.com)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

def html():
    all_the_text = ‘‘‘<html>
    <head>
        <meta charset="utf8">
        <script type="text/javascript" href="http://www.mamicode.com/jquery-3.1.0.min.js"></script>
        <style type="text/css">
        body{
            text-align: center;
        }
            .middle{
                text-align: center;
            }
            .hide{
                display: none;
            }
            .show{
                display: block;
            }
        </style>
    <title>每日数据报告</title>
    </head>
    <body>
    <h1 class="middle">‘‘‘ + yesterday1 + ‘‘‘监控数据报告</h1>
    <br>
    <div>
        <select id="sel">
            <option value="http://www.mamicode.com/op_01">xxx</option>
            <option value="http://www.mamicode.com/op_02">xxx</option>
            <option value="http://www.mamicode.com/op_03">xxx</option>
            <option value="http://www.mamicode.com/op_04">xxx</option>
        </select>
    </div>
    <br>
    <div >
        <div class="con show" id="op_01"><img src="http://www.mamicode.com/1148.png"></div>
        <div class="con hide" id="op_02"><img src="http://www.mamicode.com/1145.png"></div>
        <div class="con hide" id="op_03"><img src="http://www.mamicode.com/1079.png"></div>
        <div class="con hide" id="op_04"><img src="http://www.mamicode.com/792.png"></div>
    </div>

        <script type="text/javascript" src="http://www.mamicode.com/jquery-3.1.0.min.js"></script>
        <script type="text/javascript">
            $(‘#sel‘).change(function(){
                var cid = $(this).val();
                $(‘#‘+cid).show();
                $(‘#‘+cid).siblings().hide();
            });
        </script>
    </body>
    </html>‘‘‘

    with open(image_dir + /index.html, w) as f:
        f.write(all_the_text)

    src = /usr/monitor/day/jquery-3.1.0.min.js
    dst = /usr/monitor/day/ + yesterday + /jquery-3.1.0.min.js
    shutil.copyfile(src, dst)

if __name__==__main__:
    yesterday, yesterday1 = yesterday()
    gr_url="http://xxx/zabbix/chart2.php"
    indexURL="http://xxx/zabbix/index.php"
    username = xxx
    password = xxx
    os.mkdir(/usr/monitor/day/%s % yesterday)
    image_dir=/usr/monitor/day/+ yesterday
  
    values1={"graphid":"1148","period":86400,"stime":yesterday+000000,"width":800,"height":200}
    
    values4={"graphid":"1145","period":86400,"stime":yesterday+000000,"width":800,"height":200}
    
    values5 = {"graphid": "1079", "period": 86400, "stime": yesterday + 000000, "width": 800, "height": 200}
   
    values5_1 = {"graphid": "792", "period": 86400, "stime": yesterday + 000000, "width": 800, "height": 200}
    b=ZabbixGraph(indexURL,username,password)
    for i in (values1, values4, values5, values5_1):
        b.getgraph(gr_url, i, image_dir)

    html()
    email()

 

  说明: 这里直接将html静态页的源码write到index.html这里还需要js包,静态页可以根据自己的需求进行开发,如需要我这里的请留言吧。

 

[ python3 ] 基于zabbix 自动抓取每天监控数据