python3監控網站狀態

前面已經寫過Python3發郵件,Python發微信的文章了。直接導入即可。

import configparser,requests
from time import sleep
import WeChat,Mail

class checkurl(object):
	def __init__(self,file):
		self.file=file
		self.cfg=configparser.ConfigParser()
		
	def cfg_load(self):
		self.cfg.read(self.file)
		self.allurl=self.cfg.items('yuming')
		self.reload=self.cfg.get('time','reload')
		self.mailto=self.cfg.items('mailto')
		
	def sendmessage(self,errinfo):
		wechat.send('@all',errinfo)
		for key,values in self.mailto:
			mail.send(values,errinfo,'url訪問失敗報警')
			
	def cfg_dump(self):
		while True:
			for k,v in self.allurl:
				checknum=0
				#設置重試錯誤次數
				while checknum < 5:
					try:
						res=requests.get(v)
						print(v,res.status_code)
						res.close()
						if res.status_code >= 400:
							errinfo=v+' '+str(res.status_code)
							self.sendmessage(errinfo)
						break
					except:
						errinfo=v+' is error'
						print(errinfo+'\r\n請稍等,正在第',checknum+1,'次重試...')
						sleep(1)
						if checknum == 4:
							print('重試仍然無法連接,正在發送微信和郵件報警...')
							self.sendmessage(errinfo)
					checknum=checknum+1
			print('-----------------------------------')
			nextcheck=0
			while nextcheck < int(self.reload):
				print('距離下次檢測還剩',int(self.reload)-nextcheck,'秒')
				sleep(1)
				nextcheck=nextcheck+1

if __name__ =='__main__':
	mail=Mail.sendmail()
	wechat=WeChat.WeChat()
	check=checkurl('yuming.ini')
	check.cfg_load()
	check.cfg_dump()	


下面是yuming.ini的配置

[yuming]
yuming1=https://www.baidu.com
yuming2=http://www.qq.com
yuming3=http://www.163.com
 
[time]
reload=60
 
[mailto]
[email protected]
[email protected]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章