直接上代码::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import configparser,requests
from time import sleep
import datetime

class checkurl(object):
def __init__(self,file):
self.file=file
self.cfg=configparser.ConfigParser()

def cfg_load(self):
self.cfg.read(self.file)
self.allurl=self.cfg.items('yuming')
self.reload=self.cfg.get('time','reload')

def sendmessage(self,errinfo):
print("异常通知代码")
# 需自行实现异常通知功能

def senderror(self,errcont):
enow=datetime.datetime.now()
now=enow.strftime('%Y-%m-%d %H:%M:%S')
errfile=open('url.log','a')
errfile.write(now)
errfile.write(str(errcont))
errfile.write('\n')
errfile.close()

def cfg_dump(self):
while True:
for k,v in self.allurl:
checknum=0
#设置重试错误次数
while checknum < 5:
try:
res=requests.get(v,timeout=20)
print(v,res.status_code)
res.close()
if res.status_code >= 400:
errinfo=v+' '+str(res.status_code)
self.sendmessage(errinfo)
self.senderror(errinfo)
break
except:
errinfo=v+' is error'
print(errinfo+'\r\n请稍等,正在第',checknum+1,'次重试...')
sleep(1)
if checknum == 4:
print('重试仍然无法连接,正在发送微信和邮件报警...')
self.sendmessage(errinfo)
self.senderror(errinfo)
checknum=checknum+1
print('-----------------------------------')
nextcheck=0
while nextcheck < int(self.reload):
print('距离下次检测还剩',int(self.reload)-nextcheck,'秒')
sleep(1)
nextcheck=nextcheck+1

if __name__ =='__main__':
check=checkurl('yuming.ini')
check.cfg_load()
check.cfg_dump()

配置文件:

1
2
3
4
5
6
7
[yuming]
yuming1=https://www.baidu.com
yuming2=http://www.qq.com
yuming3=http://www.163.com

[time]
reload=60

(完)

文章抄自:郭亚彬