Python 用socket模块实现检测端口和检测web服务

本网站用的阿里云ECS,推荐大家用。自己搞个学习研究也不错
以下程序均来自《Python.UNIX和Linux系统管理指南》 http://www.linuxidc.com/Linux/2013-06/86448.htm

检测端口

check_tcp_port.py

#!/usr/bin/env python

import socket

import re

import sys

def check_server(address, port):

        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)

                return True

        except socket.error, e:

                print “Connection to %s on port %s failed: %s” % (address, port, e)

                return False

if __name__ == ‘__main__’:

        from optparse import OptionParser

        parser = OptionParser()

        parser.add_option(“-a”, “–address”, dest=”address”, default=”localhost”, help=”ADDRESS for server”, metavar=’ADDRESS’)

        parser.add_option(“-p”, “–port”, dest=”port”, type=”int”, default=80, help=”PORT for server”, metavar=”PORT”)

(options, args) = parser.parse_args()

print ‘options: %s, args: %s’ %(options, args)

check = check_server(options.address, options.port)

print ‘check_server returned %s’ % check

sys.exit(not check)

运行结果:

端口在监听

[root@CentOS python]# python check_tcp_port.py -a 192.168.137.2 -p 22

options: {‘port’: 22, ‘address’: ‘192.168.137.2’}, args: []

Attempting to connect to 192.168.137.2 on port 22

Connected to 192.168.137.2 on port 22

check_server returned True

端口不在监听

[root@centos python]# python check_tcp_port.py -a 192.168.137.2 -p 36

options: {‘port’: 36, ‘address’: ‘192.168.137.2’}, args: []

Attempting to connect to 192.168.137.2 on port 36

Connection to 192.168.137.2 on port 36 failed: [Errno 111] Connection refused

check_server returned False

检测web服务

check_web.py

#!/usr/bin/env python

import socket

import re

import sys

def check_webserver(address, port, resource):

        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

        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)

                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:

                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, Stuats: %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 ‘Staus 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@centos python]# python check_web.py -a 192.168.137.2 -p 80 -r index.html

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

HTTP request:

|||GET /index.html HTTP/1.1

Host: 192.168.137.2

|||

Attempting to connect to 192.168.137.2 on port 80

Connected to 192.168.137.2 on port 80

Received 100 bytes of HTTP response

|||HTTP/1.1 200 OK

Date: Wed, 19 Jun 2013 02:29:31 GMT

Server: Apache/2.2.3 (CentOS)

Last-Modified: |||

Closing the connection

First line of HTTP response: HTTP/1.1 200 OK

Version: HTTP/1.1, Stuats: 200, Message: OK

Success – status was 200

check_webserver returned True

不正常,找不到页面的情况

[root@centos python]# python check_web.py -a 192.168.137.2 -p 80 -r ppp.html

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

HTTP request:

|||GET /ppp.html HTTP/1.1

Host: 192.168.137.2

|||

Attempting to connect to 192.168.137.2 on port 80

Connected to 192.168.137.2 on port 80

Received 100 bytes of HTTP response

|||HTTP/1.1 404 Not Found

Date: Wed, 19 Jun 2013 02:29:41 GMT

Server: Apache/2.2.3 (CentOS)

Content-|||

Closing the connection

First line o

未经允许不得转载:演道网 » Python 用socket模块实现检测端口和检测web服务

赞 (0)
分享到:更多 ()
已有 0 条评论