python 检查站点是否可以访问

最近碰到系统有时候会访问不了,想写一个程序来检测站点是不是可以访问的功能,正好在学python,于是写了一个方法来练练手,直接上代码。

import urllib.request
import smtplib
from email.mime.text import MIMEText
import time




# 封装HTTP GET请求方法
def http_get(url, params='',headers={}):       
    if len(params)>0:
        url=url+'?'+params
    print('发起get请求:%s' % url)
    request = urllib.request.Request(url, headers)
    try:
        response = urllib.request.urlopen(request)
        #print("response.status:",response.status) 
        responseHTML = response.read().decode('utf-8')        
        return True,responseHTML,
    except Exception as e:
        msg=('发送请求get失败,原因:%s' % e)
        return False,msg

# 封装HTTP POST请求方法
def http_post(url, data='',headers={}):
    print('发起post请求:%s' % url)
    request = urllib.request.Request(url, headers)
    try:
        response = urllib.request.urlopen(request, data)
        #print("response.status:",response.status) 
        responseHTML = response.read().decode('utf-8')        
        return True,responseHTML
    except Exception as e:
        msg=('发送请求post失败,原因:%s' % e)
        return False,msg

# 封装SendMail发送邮件方法
def send_mail( recv, title, content,username='发送人邮箱@163.com', passwd='发送人邮箱密码', mail_host='smtp.163.com', port=25):
    '''
    发送邮件函数,默认使用163smtp    
    :param recv: 邮箱接收人地址,多个账号以逗号隔开
    :param title: 邮件标题
    :param content: 邮件内容
    :param username: 邮箱账号 xx@163.com
    :param passwd: 邮箱密码
    :param mail_host: 邮箱服务器
    :param port: 端口号
    :return:
    '''
    try:
        msg = MIMEText(content)  # 邮件内容
        msg['Subject'] = title  # 邮件主题
        msg['From'] = username  # 发送者账号
        msg['To'] = recv  # 接收者账号列表 (启用这一行代码,所有收件人都可以看到收件的地址,不启用只可以看到自己的地址)
        smtp = smtplib.SMTP(mail_host, port=port)  # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
        smtp.login(username, passwd)  # 发送者的邮箱账号,密码
        smtp.sendmail(username, recv.split(','), msg.as_string())
        # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
        smtp.quit()  # 发送完毕后退出smtp
        print('发送邮件成功.')
    except smtplib.SMTPException as e:
        print("发送邮件失败.",e)

#===============Main 开始=======
#本程序用来检测指定站点是否能访问,如果不能访问发邮件提示
if __name__=="__main__":
    #要检测的地址路径
    urlList=["http://www.baidu.com/","http://sys1.abc.com:9001/","http://sys2.abc.com:9005/test/check1.do?Action=check"]
    print("============检测站点是否可以访问=========================")
    print("============程序开始=====================================")
    #mail_title=""
    mail_content=""
    for url in urlList:        
        result=http_get(url)
        if(result[0]):
            #print(result[1][:100])
            #print(len(result))
            #print(result[1].find("html"))
            if result[1].find("html")<0:
                tempMsg="[ "+url+" ] 访问异常,请立即查看Server是否正常。"
                print(tempMsg)
                mail_content+=tempMsg
            else:
                tempMsg="[ "+url+" ] 访问正常,请慢慢喝茶。"
                print(tempMsg)
        else:
            #404/500
            tempMsg="[ "+url+" ] "+result[1]
            print(tempMsg)
            mail_content+=tempMsg
        print("=================================================")
    if len(mail_content)>1:#如果有网站异常才发邮件
        mail_rev="收件邮箱1@163.com,收件邮箱2@qq.com" #报错以后接受信息的邮箱
        mail_title="系统访问异常,请立即查看Server是否正常。"
        print(mail_title)
        send_mail(mail_rev,mail_title,mail_content)        
    else:
        print("所有站点检测完毕系统一切正常")
    print("============程序结束=====================================")
    time.sleep(60)#显示60秒

#===============Main 结束=======
原文地址:https://www.cnblogs.com/q149072205/p/11982282.html