歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 使用httplib模塊實現監測web服務

Python 使用httplib模塊實現監測web服務

日期:2017/3/1 9:55:36   编辑:Linux編程

以下程序均來自《Python.UNIX和Linux系統管理指南》http://www.linuxidc.com/Linux/2013-06/86448.htm

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

Copyright © Linux教程網 All Rights Reserved