最近在学习python,写了个监控网页的脚本,还有很多不足,以后再完善
主监控脚本page_check_func.py
#!/usr/bin/python2.6
import httplib import sys import subprocess
def check_webserver(address, port, resource): time = subprocess.Popen("date +'%Y-%m-%d %H:%M:%S'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) date = time.stdout.read().rstrip() #create connection if not resource.startswith('/'): resource = '/' + resource try: conn = httplib.HTTPConnection(address, port, timeout=6) print 'HTTP connection created successfully' #make request req = conn.request('GET', resource) print 'request for %s successful' % resource #get response response = conn.getresponse() print 'response status: %s' % response.status except: err_rec=open('/root/wz/python/err_rec.txt', 'a') #time = subprocess.Popen("date +'%Y-%m-%d %H:%M:%S'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #date = time.stdout.read().rstrip() err_rec.write('HTTP connection failed: %s:%s %s\n' %(address, port, date)) err_rec.close() print 'HTTP connection failed: %s:%s' % (address, port) return False finally: conn.close() print 'HTTP connection closed successfully' if response.status in [200, 301]: return True else: err_rec=open('/root/wz/python/err_rec.txt', 'a') err_rec.write('HTTP response status: %s:%s %s %s\n' %(address, port, response.status, date)) err_rec.close() if __name__ == '__main__': page_list = open('/root/wz/python/page_list.txt', 'r') for line in page_list: host_port, res = line.rstrip().split("/") host, port = host_port.split(":") check_webserver(host, port, resource=res)
|
说明:脚本中直接是调用linux中的date来记录时间的,这是因为本人对time模块不熟悉,当然
改成用time模块是更好的。
page_list.txt中放置需要监控的网页(有多少就添加多少),格式如下:
www.abc.com:80/index.php www.123.com:81/index.html
|
err_rec.txt是放置错误信息的,格式如下:
HTTP connection failed: 2010-08-26 23:59:30 HTTP response status: 404 2010-08-26 23:59:36
|
把三个文件放在/root/wz/python中,将page_check_func.py加入crontab中,每2分钟执行一次
整个部署基本上就完成了,脚本写得很粗糙很憋足,当然你可以修改脚本,用飞信连接手机报警,
或者说要监控的网站太多,可以改为多进程或多线程等等,以后有时间我在完善下整个脚本,就可
以放入生产环境中使用了。
阅读(1881) | 评论(2) | 转发(0) |