zoukankan      html  css  js  c++  java
  • python 检测nginx状态,若无法访问发邮件通知

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

    #!/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
        ),"
    ")
    
        #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()
  • 相关阅读:
    string.Join()用法
    从List分组后重新组织数据
    Java学习笔记05--字符串
    Java学习笔记03--判断与循环语句
    Java学习笔记04--数组
    Java学习笔记02--运算符、表达式
    Java学习笔记01--数据类型
    Spring面试问答
    115个Java面试题和答案——终极列表(下)
    115个Java面试题和答案——终极列表(上)
  • 原文地址:https://www.cnblogs.com/rayong/p/8399794.html
Copyright © 2011-2022 走看看