#!/usr/bin/env python
# __*__coding:utf8__*__
#Author:wangpengtai
#Blog:http://wangpengtai.blog.51cto.com/
import pycurl
import sys
import StringIO #引用该模块的原因是:使用pycurl后会打印出页面内容,我们不需要看到这个内容,只需要获取页面反馈信息就行了,只能将其写入缓存中,目前没找到好办法,学艺不精,不会使用重定向写到os.devnull中,无奈初次下策。。。
#开始使用的是写入临时文件,但是会有权限问题,导致zabbix无法获取到数据。
class WebStatus( object ):
def __init__( self , url):
self .url = url
self .curl = pycurl.Curl()
self .string = StringIO.StringIO()
# 连接等待时间,0则不等待
self .curl.setopt(pycurl.CONNECTTIMEOUT, 5 )
# 超时时间
self .curl.setopt(pycurl.TIMEOUT, 5 )
# 下载进度条,非0则屏蔽
self .curl.setopt(pycurl.NOPROGRESS, 1 )
# 指定HTTP重定向最大次数
self .curl.setopt(pycurl.MAXREDIRS, 5 )
# 完成交互后强制断开连接,不重用
self .curl.setopt(pycurl.FORBID_REUSE, 1 )
# 设置DNS信息保存时间,默认为120秒
self .curl.setopt(pycurl.DNS_CACHE_TIMEOUT, 60 )
# 设置请求的Url
self .curl.setopt(pycurl.URL, self .url)
self .curl.setopt(pycurl.WRITEFUNCTION, self .string.write) #将页面内容写入缓存
self .curl.perform()
def request_value( self ):
data = {
"Http_code" : self .curl.getinfo(pycurl.HTTP_CODE),
"Speed_download" : self .curl.getinfo(pycurl.SPEED_DOWNLOAD),
"Connect_time" : self .curl.getinfo(pycurl.CONNECT_TIME),
"Total_time" : self .curl.getinfo(pycurl.TOTAL_TIME),
"Dnslookup_time" : self .curl.getinfo(pycurl.NAMELOOKUP_TIME),
"Redirect_time" : self .curl.getinfo(pycurl.REDIRECT_TIME),
"Redirect_count" : self .curl.getinfo(pycurl.REDIRECT_COUNT)
}
return data
def __end__( self ): #释放内存和连接,做一个有始有终,有责任心的运维狗
self .string.close()
self .curl.close()
if __name__ = = "__main__" :
Usage = """
Usage: python web_monitor.py url [Http_code|Speed_download|Connect_time|Total_time|Dnslookup_time|Redirect_time|Redirect_count]
"""
try :
url = sys.argv[ 1 ]
request = sys.argv[ 2 ]
try :
s = WebStatus(url)
try :
print s.request_value()[request]
except KeyError:
print "Make sure 2nd argument is right!"
except pycurl.error:
print "Make sure the url is right or reachable!"
except IndexError:
print "Must be 2 arguments given!%s" % Usage
|