Monitor the status of a Web server with a Python script

Source: Internet
Author: User
Tags http request resource socket split python script

By detecting a test page in the Web to get an HTTP status code to judge the state of the Web server, the source script comes from the Internet, where you can make a small comment for the study of children's shoes like 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 ('/'): #判断是否以 '/' Start
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 sockets
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 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 ' 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 to 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的解析函数, use the resolved options in the options, using the other positional parameters in the 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 ': ' 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 bytes of HTTP response
||| http/1.1 OK
date:wed, 2013 01:19:06 GMT
server:bws/1.0
content-length:9777
content| | |
Closing the connection
The The HTTP response:http/1.1 OK
version:http/1.1, status:200, Message:ok
Success-status was 200
Check_webserver returned True

Note: The meaning of the parameters in Add_option ():

Short option string: For the first argument, the abbreviation for option, such as-F;

Long option string: For the second argument, the full spell for option, for example,--file;

The parameters that follow are named parameters, and the named arguments are optional parameters:

Action=: Indicates how this option is handled, and the default value is the store, which indicates that the value of the option is stored in the member of the resolved Options object. Action can also have other values: for bool values, use Store_true to default to store true, use Store_false to store the default storage False,store_const to store the const set value to this option, Append indicates that the option is added to the list, at which point this option is a list, may contain multiple values, and count represents an increase to counter, callback to invoke the specified function. All the action values are as follows:

Store + store_true + store_false + store_const + Append + Count + callback

Type=: The type that represents the value of this option, which defaults to string and can be specified as string, int, choice, float and complex;

Dest=: Represents the name of the member of this option in the options object after the Optionparser resolution, using the long option string by default;

Default=: Represents the default value for option;

Metavar=: Represents the default value displayed to option in Help;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.