加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

python socket 检查服务器端口及返回状态码

(2012-09-25 10:33:27)
标签:

育儿

分类: python
[root@vm046 python.Uninx_Linux]# cat check_http.py
#!/usr/bin/python

import socket
import re
import sys
from optparse import OptionParser

def check_webserver(address,port,resource):
        #build up HTTP request string
        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

        #create a 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)
                #we should only need the first 100 bytes or so
                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:
                #be a good citizen and close your connection
                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
        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@vm046 python.Uninx_Linux]# python check_http.py --help
Usage: check_http.py [options]

Options:
  -h, --help            show this help message and exit
  -a ADDRESS, --address=ADDRESS
                        ADDRESS for webserver
  -p PORT, --port=PORT  PORT for webserver
  -r RESOURCE, --resource=RESOURCE
                        RESOURCE to check

应用:
[root@vm046 python.Uninx_Linux]# python check_http.py -a 10.0.0.43 -p 80 -r index.html
options: {'resource': 'index.html', 'port': 80, 'address': '10.0.0.43'},args: []
HTTP request:
|||GET /index.html HTTP/1.1
Host: 10.0.0.43

|||
Attempting to connect to 10.0.0.43 on port 80
Connected to 10.0.0.43 on port 80
Received 100 bytes of HTTP response
|||HTTP/1.1 301 Moved Permanently
Date: Tue, 25 Sep 2012 02:35:04 GMT
|||ver: Apache/2.2.3 (Red Hat)
Closing the connection
First line of HTTP response: HTTP/1.1 301 Moved Permanently
Version: HTTP/1.1, Status: 301, Message: Moved Permanently
Success - status was 301
check_webserver returned True

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有