我的github地址https://github.com/nongxl/checkLinks

项目在github已更新,目前可通过配置文件配置需检测的网站和对应的负责人。请移步github

批量测试链接地址是否正常,发现网站不能访问时自动发送邮件,同时运维很多个项目的时候这个脚本就很有用了。

如果需要检测的系统都在局域网,就把代码里的百度测试地址改成局域网中一个稳定的、可以用作基准的地址。但是不能发邮件了。

windows下需要把日志的路径改为绝对路径。如"c:\\checklinks\\logs.log" 。

发送邮箱我是用163,需要提前设置好smtp,并且建议开启客户端授权密码;

注释详细,没别的可说了。代码结构写得不太好,希望高手指教。

运行效果:

运行效果

from urllib.request import urlopen
from urllib import request
import requests,re,chardet
from prettytable import PrettyTable
import yagmail
import datetime
receivers = ['123@qq.com','456@qq.com']
#链接邮箱服务器
yag = yagmail.SMTP( user="cks@163.com", password="passw0rd", host='smtp.163.com')
logs = open('.\logs.log',encoding='utf-8',mode='a+')

urls = [
    'https://mail.qq.com',
    'https://www.12306.cn/',
    'https://www.ithome.com',
    'https://www.taobao.com',
    'https://www.adobe.com',
    'https://www.csdn.net',
    'http://www.microsoft.com',
    'https://github.com'
    'https://www.google.com'
    ]

#通过正则匹配<title>标签的内容判断网页标题
def get_title(html):
    tar = '<title>.*?</title>'
    tar = re.compile(tar, re.IGNORECASE)#不区分大小写,否则不同编码时<TITLE></TITLE>标签为大写匹配不出来
    target = re.findall(tar,html)
    if target:
        title = target[0]
        #对获取的title做进一步处理,取第七位之后和倒数第八位之前的内容作为网页标题
        title = title[7:-8]
        return title

'''
颜色显示的格式:
\ 033 [显示方式;字体色;背景色m ...... [\ 033 [0m]
显示颜色的参数:
显示方式 	    效果 	    字体色 	    背景色 	    颜色描述
0 	      终端默认设置 	      30 	      40 	      黑色
1 	          高亮显示 	      31 	      41 	      红色
4 	        使用下划线 	      32 	      42 	      绿色
5 	            闪烁 	      33 	      43 	      黄色
7 	          反白显示 	      34 	      44 	      蓝色
8 	           不可见 	      35 	      45 	     紫红色
		                      36 	      46 	     青蓝色
		                      37 	      47 	      白色
'''
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
headers = { 'User-Agent':user_agent }
table = PrettyTable(['编号','系统名称','系统地址','网络状态','耗时(秒)','检查结果'])
timelap = 0
code = 0
isSandMail = 0
try:
    netCheck = urlopen('http://www.baidu.com').getcode()#访问百度测试网络连接
    print(str(datetime.datetime.now())+"\033[1;32;m 网络连接正常,开始检查... \033[0m")
    for url in urls:
        try:
            req = request.Request(url, None, headers)
            resp = request.urlopen(req)
            #获取状态码
            code = resp.getcode()
            #获取响应时间
            timelap = requests.get(url).elapsed.total_seconds()
            html = resp.read()
            #识别网页编码方式
            charset = chardet.detect(html)
            #按网页的编码方式解码,否则会乱码报错
            html = str(html,charset['encoding'])
            title = get_title(html)
            #将检查结果添加到表格中
            table.add_row([urls.index(url)+1,title,url,code,timelap,"\033[0;32;m 连接成功 \033[0m"])

        except Exception as e:
            #将异常也添加到表格中
            err = str(e)
            table.add_row([urls.index(url) + 1, "null", url, err, timelap, "\033[0;31;m 连接错误 \033[0m"])
            isSandMail = 1

except Exception as e:
    #如果不能访问百度,判断为网络错误
    print(str(datetime.datetime.now())+"\033[1;31;m 网络检查错误,不能访问外网。请先检查本机网络 \033[0m\n",e)
    logs.write(str(datetime.datetime.now())+'\t'+'网络错误'+'\n')

print(table)
logs.write(str(datetime.datetime.now())+'\t'+'检查完成'+'\n')
if isSandMail == 1:
    #发送邮件
    try:
        yag.send(receivers,'运维邮件:网站无法访问。请尽快处理',str(table))
        logs.write(str(datetime.datetime.now())+'\t'+'运维邮件发送成功'+'\n')
    except Exception as sendErr:
        print('邮件发送失败'+str(sendErr))
        logs.write(str(datetime.datetime.now())+'\t'+'邮件发送失败'+str(sendErr)+'\n'+str(table)+'\n')
logs.close()

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐