Python脚本检测网站存活性
#!/usr/bin/env python
#coding:utf-8
# 探测网站访问的存活状态,并对异常网站进行邮件报警
# 需要安装第三方模块requests: pip3 install requests
import os, requests
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# urls.txt为检测网址文件,一个网址一行,与脚本放在同一目录
urllist = os.path.dirname(os.path.realpath(__file__)) + '/urls.txt'
list = []
contents = ''
# 邮件参数设置
msg_from = 'xxxxxx@qq.com'
auth_code = '**********'
msg_to = 'XXXXXXXXXX@126.com'
def check_status():
lines = ''
log = ''
try:
with open(urllist, 'r') as url:
lines = url.readlines()
except Exception as e:
print('File error:' + str(e))
#print('%s is not open or not exist!' % urllist)
for line in lines:
list.append(line.strip())
for i in list:
esponse = requests.get(i)
code = response.status_code
log += i + ' is ' + str(code) + '\n'
if code in [200, 301, 302]:
continue
global contents
contents += i + ' ' + str(code) + ' is down!\n'
file = open(os.path.dirname(os.path.realpath(__file__)) + '/log.txt', 'w')
file.write(log)
def send_mail(content):
subject = 'server warning'
msg = MIMEText(content, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL('smtp.qq.com', 465)
s.login(msg_from, auth_code)
s.sendmail(msg_from, msg_to, msg.as_string())
s.close()
return 1
except Exception as e:
return 0
if __name__ == '__main__':
check_status()
if(contents.strip() != ''):
send_mail(contents)
# crontab -e
# */5 * * * * /usr/bin/python /usr/local/sbin/http_status.py >>/tmp/http_status.error.log 2>&1
留言评论