zoukankan      html  css  js  c++  java
  • [ 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+' 重点监控数据报告已生成。
    请访问: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="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="op_01">xxx</option>
                <option value="op_02">xxx</option>
                <option value="op_03">xxx</option>
                <option value="op_04">xxx</option>
            </select>
        </div>
        <br>
        <div >
            <div class="con show" id="op_01"><img src="1148.png"></div>
            <div class="con hide" id="op_02"><img src="1145.png"></div>
            <div class="con hide" id="op_03"><img src="1079.png"></div>
            <div class="con hide" id="op_04"><img src="792.png"></div>
        </div>
    
            <script type="text/javascript" src="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包,静态页可以根据自己的需求进行开发,如需要我这里的请留言吧。

  • 相关阅读:
    Django准备知识-web应用、http协议、web框架、Django简介
    Django
    MySQL(基本语句)
    jsvascript === 和==的区别
    控制input只能输入1-200范围的数字
    删除数组中指定的某个元素
    微信授权登陆绑定
    通过GZ代替document.getElementById()
    判断浏览器版本
    截取逗号后面所有字符
  • 原文地址:https://www.cnblogs.com/hukey/p/6042482.html
Copyright © 2011-2022 走看看