通过python检测端口的实用代码
#!/usr/bin/env python import socket import re import sys def check_server(address, port): #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) 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@SVN ~]# ./port_checker_tcp.py -a 192.168.3.160 -p 80
options: {‘port’: 80, ’address’: ’192.168.3.160′}, args: []
Attempting to connect to 192.168.3.160 on port 80
Connected to 192.168.3.160 on port 80
check_server returned True
错误返回:
[root@SVN ~]# ./port_checker_tcp.py -a 192.168.3.160 -p 808
options: {‘port’: 808, ’address’: ’192.168.3.160′}, args: []
Attempting to connect to 192.168.3.160 on port 808
Connection to 192.168.3.160 on port 808 failed: (111, ’Connection refused’)
check_server returned False