python 檢測nginx狀態,若沒法訪問發郵件通知

應用場景:用來檢測網站可用性,訪問失敗,則發郵件通知python

#!/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,"465")
    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()
相關文章
相關標籤/搜索