通過檢測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.6688.cc -r index.php
options: {'resource': 'index.php', 'port': 80, 'address': 'www.6688.cc'}, args: []
HTTP request:
|||GET /index.php HTTP/1.1
Host: www.6688.cc
|||
Attempting to connect to www.6688.cc on port 80
Connected to www.6688.cc 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的默認值;