定时检测网测速

安装测试工具。官网www.speedtest.net
pip install speedtest-cli

使用下面脚本,每天随机找3个服务器测试一下,发到指定用户的邮箱里。

#!/bin/env python
# -*- coding:utf-8 -*-
# Date:        2017-05-10
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import os, sys
import random
from string import strip

import smtplib
from email.mime.text import MIMEText
 
#### 基础设置
mail_host = 'smtp.exmail.qq.com'
mail_user = 'warning'
mail_pwd = 'aaa'
mail_to = "simon-zzm@163.com"
mail_cc = "simon-zzm@"
 
 
####
def mail_send(text):
    content = '%s' % text
    msg = MIMEText(content)
    msg['From'] = mail_user
    msg['Subject'] = 'dsg net report'
    msg['To'] = mail_to
    msg['CC'] = mail_cc
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user, mail_pwd)
        s.sendmail(mail_user, [mail_to, mail_cc], msg.as_string())
        s.close()
    except Exception, e:
        print e

def speedTestStatus(serverId):
    getData = os.popen('/usr/local/bin/speedtest-cli --server=%s --share' % serverId).readlines()
    for oneData in getData:
        if oneData[-1] == '\n':
            oneData = oneData[:-1]
        if oneData.find('Download:') > -1:
            download = strip(oneData).split(' ')
            downStatus = "%s%s" % (download[1], download[2])
        if oneData.find('Upload:') > -1:
            upload = strip(oneData).split(' ')
            upStatus = "%s%s" % (upload[1], upload[2])
        if oneData.find('Share results:') > -1:
            pic = strip(oneData).split(' ')
            picStatus = "%s" % (pic[-1])
    return downStatus, upStatus, picStatus


def getChainServerList():
    getData = os.popen('/usr/local/bin/speedtest-cli --list|grep -i china').readlines()
    idList = []
    for oneData in getData:
        idList.append(strip(oneData.split(') ')[0]))
    return idList

def main():
    # 查找测试服务器中国服务器id
    # 并随机选出三个
    getID = random.sample(getChainServerList(), 3)
    # 进行测试,并返回结果。
    context = ""
    for oneId in getID:
        down, up, pic = speedTestStatus(oneId)
        context = "%s testId:%s down:%s up:%s pic:%s\n" % (context, oneId, down, up, pic)
    mail_send(context)

if __name__ == '__main__':
    main()

发表评论

电子邮件地址不会被公开。 必填项已用*标注