標籤:
最近公司erp伺服器無規律、不間斷、時不時抽風,往往都是掛了快個把小時後其它部門的人才打電話過來說伺服器掛了。於是用python寫了一個簡單的網頁監控。程式主要監控網頁狀態代碼,200為正常,否則視為伺服器掛了。每隔70秒查詢一次,若發現三次連續的查詢中都報錯誤,則通過預先設定的郵箱發送警告郵件。郵件發送後隔30分鐘再次監控設定網頁。
#coding:utf-8#author:ljc#python verson 2.7.9import smtplibimport urllibimport timedef sendmail(): mail_to = smtplib.SMTP(‘smtp.126.com‘,25) #設定郵件發送伺服器 mail_to.login("[email protected]","[email protected]#") #設定發送郵件的帳號,密碼 msg = """From: system <[email protected]> To: <[email protected]>Subject: webserver_downweb server is down """ mail_to.sendmail(‘[email protected]‘,‘[email protected]‘,msg) mail_to.close()if __name__ == ‘__main__‘:
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),‘server monitor is running‘ while 1: count=0 error_status_count=0 while count<3: time.sleep(70) #每隔70秒監控一次伺服器 try: status=urllib.urlopen("http://192.168.0.8").code #收集監控網址的網頁狀態代碼 if status==200: print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),‘web server is functional‘ if status<>200: error_status_count+=1 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),‘web servier is down ,error status count:‘,error_status_count,‘status number‘,status except: error_status_count+=1 #網頁狀態錯誤次數進行累加 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),‘web servier is down ,error status count:‘,error_status_count count+=1 if error_status_count>=3: #網頁狀態錯誤超過3次自動發送警示郵件 print ‘error status count is :‘,error_status_count,‘sending email,the program wiil try to monint the server after half an hour‘ sendmail() time.sleep(1800) #郵件發送後半小時再後再次監控網頁
python監控網頁狀態