python 检测nginx状态,若无法访问发邮件通知

时间:2024-07-04 13:05:20

应用场景:用来检测网站可用性,访问失败,则发邮件通知

#!/usr/bin/env python
import urllib2,time,smtplib,string,logging
from conf import * logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/var/log/status.log',
filemode='a') def send_mail(name,url):
HOST = "smtp.126.com"
SUBJECT = name + " " + url + " " + "Domain name cannot be accessed"
TO = "2712578342@qq.com"
FROM = "acd34yss@126.com"
text = name + " " + url
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT,
"",
text
),"\r\n") #server = smtplib.SMTP()
#server.connect(HOST,"465")
#server.starttls()
server = smtplib.SMTP_SSL(HOST,"")
server.set_debuglevel(True)
logging.info(server.ehlo())
server.login("acd34yss@126.com","password")
server.sendmail(FROM,[TO],BODY)
server.quit() def show_status(key,url):
try:
req = urllib2.Request(url)
req.add_header('Referer', url)
req.add_header('User-Agent','Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A456 Safari/602.1',) #目标网站是手机h5,所以请求头模拟手机浏览器
response = urllib2.urlopen(req).code
except urllib2.URLError,e:
send_mail(key,url[7:]) #发送邮件内容不能包含http,所以从http后面开始截取邮件内容
logging.warning(e) #打印错误日志到文件中 def main():
for (key,url) in info['host']['all_url'].items():
show_status(key, url)
time.sleep(2) if __name__=="__main__":
main()