[ 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="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包,靜態頁可以根據自己的需求進行開發,如需要我這里的請留言吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM