Python 使用httplib模块实现监测web服务

以下程序均来自《Python.UNIX和Linux系统管理指南》

httplib_check_web.py

#!/usr/bin/env python

import httplib

import sys

def check_webserver(address, port, resource):

if not resource.startswith('/'):

resource = '/' + resource

try:

conn = httplib.HTTPConnection(address, port)

print 'HTTP connection created successfully'

req = conn.request('GET', resource)

print 'request for %s successful' % resource

response = conn.getresponse()

print 'response status: %s' % response.status

except httplib.error, e:

print "HTTP connection failed: %s" % e

return False

finally:

conn.close()

print 'HTTP connection closed successfully'

if response.status in [200, 301]:

return True

else:

return False

if __name__ == '__main__':

from optparse import OptionParser

parser = 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")

(options, args) = parser.parse_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)


运行结果:

成功

[root@CentOS python]# python httplib_check_web.py -a 192.168.137.2 -r index.html

options: {'resource': 'index.html', 'port': 80, 'address': '192.168.137.2'}, args: []

HTTP connection created successfully

request for /index.html successful

response status: 200

HTTP connection closed successfully

check_webserver returned True

不成功,网页不存在的情况

[root@centos python]# python httplib_check_web.py -a 192.168.137.2 -r ppp.html

options: {'resource': 'ppp.html', 'port': 80, 'address': '192.168.137.2'}, args: []

HTTP connection created successfully

request for /ppp.html successful

response status: 404

HTTP connection closed successfully

check_webserver returned False

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/7c4768d5f272fa839f81164cf1a1acf5.html