Skip to content

Instantly share code, notes, and snippets.

@NoAnyLove
Last active December 16, 2015 19:19
Show Gist options
  • Save NoAnyLove/5484467 to your computer and use it in GitHub Desktop.
Save NoAnyLove/5484467 to your computer and use it in GitHub Desktop.
自用的用于监控网站是否能正常访问的脚本。 最近感觉自己的博客访问不怎么稳定,好几次自己都访问不了,用了监控宝,不过免费版的监控频率实在是太低了,15分钟一次,于是干脆自己写一个简单的脚本实现。 话说其实我是把它部署在自己的Host1Free的免费VPS上的,Koding上也部署了一个,感觉还行吧,至少监控频率高了很多。 写的比较乱,暂时就这样吧,抽空写博客说明下。 另外还有改进的点子,想多部署几个地方,然后把信息汇总到一个网站上用于查看,不过暂时没时间弄,下次有空再说(主要是不会数据库,Orz)
#! /usr/bin/python
#coding:utf-8
import requests
import logging
import time
#自用的用于监控网站是否能正常访问的脚本
#话说其实我是把它部署在自己的Host1Free的免费VPS上的
#写的比较乱,暂时就这样吧,抽空写博客说明下。另外还有改进的点子,不过暂时没时间弄
#################需要修改的参数############
__url="http://127.0.0.1"
__check_time=180
__retry_time=30
__keyword='Thanks'
__timefm="%Y-%m-%d %a %H:%M:%S +0800"
########################################
def GetTime():
return time.strftime(__timefm, time.gmtime(time.time()+8*60*60))
def error(msg, *args, **kwargs):
logger.error(GetTime()+" "+msg, *args, **kwargs)
def info(msg, *args, **kwargs):
logger.info(GetTime()+" "+msg, *args, **kwargs)
#Setting up the logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
file = logging.FileHandler("WebSite.log")
logger.addHandler(file)
IsDown=False
DownTime=0
#开始循环监控
while True:
try:
r=requests.get(__url)
except:
error("无法访问目标")
if IsDown:
#如果上一次就访问失败,就将访问失败时间+__retry_time秒
#DownTime=DownTime+__retry_time
#因为每次连接的时候会有一定时间消耗,所以取消这个计时方法
pass
else:
#如果上一次访问正常,将IsDown置位,并从现在开始计时
IsDown=True
DownTime=time.time()
#如果无法访问,延迟30秒继续尝试
time.sleep(__retry_time)
continue
if r.status_code<>200:
error(GetTime()+" Status Code异常( status_code=%d )", r.status_code)
#r.content的类型是str,这里应该是采用Response头中声明的utf-8进行编码
#r.text的类型是Unicode,是已经被转为了Python内部的Unicode
#如果用于检查的__keyword关键字中包含了中文,就需要注意编码问题了
if r.text.find(__keyword.decode('utf-8'))<>-1:
#如果上一次访问失败,现在说明能正常访问了
if IsDown:
IsDown=False
error("恢复访问,此次故障持续时间为%d分钟", int((time.time()-DownTime)/60))
info("访问正常")
else:
error('关键字[%s]不匹配',__keyword)
r.close()
#延迟180秒,进行下一次检查
time.sleep(__check_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment