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 結束=======

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM