通过检测web的一个测试页来获取http状态码判断web server的状态,源脚本来自互联网,在此做小小的注释,供喜欢python的童鞋学习研究。
#!/usr/bin/env python
#script name check_web_stat.py
import socket #tcp建立socket连接用到
import re #正则表达式模块
import sys
def check_webserver(address, port, resource):
#建立http请求串
if not resource.startswith(‘/’): #判断是否以‘/’开头
resource = ‘/’ + resource
request_string = “GET %s HTTP/1.1\r\nHost: %s\r\n\r\n” % (resource, address)
print ‘HTTP request:’
print ‘|||%s|||’ % request_string
#创建一个 TCP socket
s = socket.socket()
print “Attempting to connect to %s on port %s” % (address, port)
try:
s.connect((address, port))
print “Connected to %s on port %s” % (address, port)
s.send(request_string)
#获取前100个字节
rsp = s.recv(100)
print ‘Received 100 bytes of HTTP response’
print ‘|||%s|||’ % rsp
except socket.error, e:
print “Connection to %s on port %s failed: %s” % (address, port, e)
return False
finally:
#关闭socket连接
print “Closing the connection”
s.close()
lines = rsp.splitlines() #将一个段落的字符串以行为单位分割成一个列表
print ‘First line of HTTP response: %s’ % lines[0]
try:
version, status, message = re.split(r’\s+’, lines[0], 2)
print ‘Version: %s, Status: %s, Message: %s’ % (version, status, message)
except ValueError:
print ‘Failed to split status line’
return False
if status in [‘200’, ‘301’]:
print ‘Success – status was %s’ % status
return True
else:
print ‘Status was %s’ % status
return False
if __name__ == ‘__main__’:
from optparse import OptionParser #导入optionparser命令行工具模块
parser = OptionParser() #构造optionparser的对象
parser.add_option(“-a”, “–address”, dest=”address”, default=’localhost’,
help=”ADDRESS for webserver”, metavar=”ADDRESS”)
parser.add_option(“-p”, “–port”, dest=”port”, type=”int”, default=80,
help=”PORT for webserver”, metavar=”PORT”)
parser.add_option(“-r”, “–resource”, dest=”resource”, default=’index.html’,
help=”RESOURCE to check”, metavar=”RESOURCE”)
#往optionparser对象中增加option :parser.add_option()
(options, args) = parser.parse_args() #调用optionparser的解析函数,在options中使用解析到的options,在args中使用其他的位置参数args
print ‘options: %s, args: %s’ % (options, args)
check = check_webserver(options.address, options.port, options.resource)
print ‘check_webserver returned %s’ % check
sys.exit(not check)
# python check_web_stat.py -a www.baidu.com -r index.php
options: {‘resource’: ‘index.php’, ‘port’: 80, ‘address’: ‘www.baidu.com’}, args: []
HTTP request:
|||GET /index.php HTTP/1.1
Host: www.baidu.com
|||
Attempting to connect to www.baidu.com on port 80
Connected to www.baidu.com on port 80
Received 100 bytes of HTTP response
|||HTTP/1.1 200 OK
Date: Wed, 09 Jan 2013 01:19:06 GMT
Server: BWS/1.0
Content-Length: 9777
Content|||
Closing the connection
First line of HTTP response: HTTP/1.1 200 OK
Version: HTTP/1.1, Status: 200, Message: OK
Success – status was 200
check_webserver returned True
注:add_option()中参数的意义:
short option string: 为第一个参数,表示option的缩写,例如-f;
long option string: 为第二个参数,表示option的全拼,例如–file;
后面的参数皆为命名参数,命名参数为可选参数:
action=: 表示对此option的处理方式,默认值为store,表示存储option的值到解析后的options对象的成员中。action还可以有其他的值:对于bool值,使用store_true来默认存储true,使用store_false来默认存储false,store_const用来存储const设置的值到此option,append表示增加option的参数到list中,此时此option是一个list,可能包含多个值,count表示对counter增加一,callback表示调用指定的函数。所有的action值如下:
store + store_true + store_false + store_const + append + count + callback
type=:表示此option的值的类型,默认为string,可以指定为string, int, choice, float and complex;
dest=:表示此option在经过optionparser解析后的options对象中成员的名字,默认使用long option string;
default=:表示比option的默认值;
metavar=:表示显示到help中option的默认值;