欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

python抓取cacti的流量圖

??有一個(gè)功能需求,每天在cacti上爬取昨天一整天的流量圖,并將流量圖上的min、max、average流量做成表格,用郵件發(fā)出。 (python2.7.5)

成都創(chuàng)新互聯(lián)是一家專業(yè)提供開(kāi)封企業(yè)網(wǎng)站建設(shè),專注與成都做網(wǎng)站、網(wǎng)站建設(shè)、H5場(chǎng)景定制、小程序制作等業(yè)務(wù)。10年已為開(kāi)封眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。

??1、需要使用的模塊

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import time,datetime,cookielib,requests,sys,re,urllib2,urllib,socket,csv,heapq
import smtplib
import mimetypes
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.MIMEImage import MIMEImage
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)

??2、登陸cacti的函數(shù)

def Login1():
    socket.setdefaulttimeout(10)
    global headers
    headers={}
    cj = cookielib.CookieJar()
    global opener
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

    # cacti使用的賬號(hào)密碼
    data = urllib.urlencode( {'action':'login','login_username':'admin','login_password':'123456' })
    # 打開(kāi)cacti主頁(yè)
    page = urllib2.Request("http://100.0.102.3/index.php", data ,headers)
    # 爬取頁(yè)面數(shù)據(jù)
    html = opener.open(page).read()
    # 如果頁(yè)面數(shù)據(jù)中有g(shù)raph_settings.php鏈接,說(shuō)明登陸成功(返回1),反之登陸失敗(返回0)
    if re.findall("graph_settings.php",html):
        return 1
    else:
        return 0

??3、再定義幾個(gè)需要用到的函數(shù)

# 日期轉(zhuǎn)換為時(shí)間戳(cacti的圖片網(wǎng)址需要指定開(kāi)始和結(jié)束時(shí)間)
def datetime_timestamp(dt):
     time.strptime(dt, '%Y-%m-%d %H:%M:%S')
     s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
     return int(s)

# 將bit換算成Gbit/Mbit/Kbit(各級(jí)相差1000倍,保留2位小數(shù))
def tobit(x):
    if x>=1000000000:
        return str(round(x/1000000000,2))+'G'
    elif x>=1000000:
        return str(round(x/1000000,2))+'M'
    elif x>=1000:
        return str(round(x/1000,2))+'K'
    else:
        return str(round(x,2))

??4、開(kāi)始抓取圖片和csv(如下圖,圖片右邊的藍(lán)色下載箭頭就是csv)。
python抓取cacti的流量圖
python抓取cacti的流量圖

try:
    # 如果登陸成功
    if Login1()==1:
        # 流量圖的開(kāi)始時(shí)間,昨天的00:00:00
        start_time=str(datetime_timestamp((datetime.datetime.today()-datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00')))
        # 流量圖的結(jié)束時(shí)間,今天的00:00:00
        end_time=str(datetime_timestamp(datetime.datetime.today().strftime('%Y-%m-%d 00:00:00')))

        # 昨天一整天的流量圖網(wǎng)址(2687是圖片id)
        url1="http://100.0.102.3/graph_image.php?action=zoom&local_graph_id=2687&rra_id=0&view_type=&graph_start="+start_time+"&graph_end="+end_time
        # 下載圖片,保存到本地
        request = urllib2.Request(url1, None ,headers)
        res = opener.open(request).read()
        f=open("/myftpdir/2687.png","wb")
        f.write(res)
        f.close()
        # 下載圖片對(duì)應(yīng)的csv(用于讀取max、min等數(shù)值)
        url2="http://100.0.102.3/graph_xport.php?local_graph_id=2687&rra_id=0&view_type=&graph_start="+start_time+"&graph_end="+end_time
        request = urllib2.Request(url2, None ,headers)
        res = opener.open(request).read()
        f=open("/myftpdir/2687.csv","wb")
        f.write(res)
        f.close()

        # 讀取這個(gè)csv文件
        f=open('/myftpdir/2687.csv','rb')
        reader = csv.reader(f)
        # csv保存了每5分鐘的平均上傳(outbound)和下載(inbound)速率(共288行),生成2個(gè)列表來(lái)存儲(chǔ)所有的上傳速率和下載速率
        inbounds=[]
        outbounds=[]

        n=0
        for row in reader:
            # 該表格的第11行到298行是速率
            if n>=10 and n<=297:
                # 如果數(shù)據(jù)顯示NaN,則表示cacti當(dāng)時(shí)獲取數(shù)據(jù)失敗,這種情況不做存儲(chǔ)
                # csv第1列是時(shí)間,第2列是inbound,第3列是outbound
                if row[1]!='NaN':
                    inbounds.append(float(row[1]))
                if row[2]!='NaN':
                    outbounds.append(float(row[2]))            
            n+=1

        # inbound平均速率=inbounds列表的所有速率總和/列表長(zhǎng)度(就是存儲(chǔ)的速率個(gè)數(shù)),并換算單位
        inbound_ave1=tobit(float(reduce(lambda x,y:x+y,inbounds)/len(inbounds)))
        # inbounds列表的最小值
        inbound_min1=tobit(heapq.nsmallest(1,inbounds)[0])
        # inbounds列表的最大值
        inbound_max1=tobit(heapq.nlargest(1,inbounds)[0])
        # 同樣方法計(jì)算outbound的平均速率、最大速率、最小速率
        outbound_min1=tobit(heapq.nsmallest(1,outbounds)[0])
        outbound_max1=tobit(heapq.nlargest(1,outbounds)[0])
        outbound_ave1=tobit(float(reduce(lambda x,y:x+y,outbounds)/len(outbounds)))

??5、發(fā)送郵件


        # 指定發(fā)件人、收件人、標(biāo)題等
        msg = MIMEMultipart('related')
        msg['From'] = "1111111@qq.com"
        # 郵件標(biāo)題按要求做成”X年X月X日?qǐng)?bào)表“
        msg['Subject'] =str((datetime.datetime.today()-datetime.timedelta(days=1)).strftime('%Y'))+u'年'+str((datetime.datetime.today()-datetime.timedelta(days=1)).strftime('%m'))+u'月'+str((datetime.datetime.today()-datetime.timedelta(days=1)).strftime('%d'))+u'日?qǐng)?bào)表'
        msg['To']="111111@qq.com"
        toaddrs = [msg['To']]

        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)

        # 流量圖加入郵件正文
        fp = open('/myftpdir/2687.png', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image1>')
        msg.attach(msgImage)

        # 郵件正文,因?yàn)橐砑訄D片和表格,所以不能用純文本格式,改用html格式
        msgText = MIMEText('''
            <h5>流量圖:</h5>
            <img src="cid:image1">
            <br>
            <table border="1">
                <tr>
                    <th>出口</th>
                    <th>最小值</th>
                    <th>平均值</th>
                    <th>最大值</th>
                </tr>
                <tr>
                    <th>inbound</th>
                    <th>%s</th>
                    <th>%s</th>
                    <th>%s</th>
                </tr>
                <tr>
                    <th>outbound</th>
                    <th>%s</th>
                    <th>%s</th>
                    <th>%s</th>
                </tr>
            </table>
            ''' % (inbound_min1,inbound_ave1,inbound_max1,outbound_min1,outbound_ave1,outbound_max1), 'html', 'utf-8')

        msgAlternative.attach(msgText)

        # 連接郵箱服務(wù)器
        server = smtplib.SMTP()
        server.connect('smtp.qq.com',25)
        server.ehlo()
        server.login('111111@qq.com','123456')
        server.sendmail(msg['From'],toaddrs,msg.as_string())
        server.quit()         
except:
    # 登陸失敗
    pass

??郵件內(nèi)容:

python抓取cacti的流量圖

網(wǎng)站名稱:python抓取cacti的流量圖
URL分享:http://chinadenli.net/article36/ihoopg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站App開(kāi)發(fā)企業(yè)建站靜態(tài)網(wǎng)站網(wǎng)站設(shè)計(jì)公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化