一个检测TCP端口的Python脚本程序,默认需要两个参数,一个是-a参数,后面接要检测的IP地址,另一个是-p参数,后面接要检测的IP地址的端口,如果省略该选项,默认是IP地址80端口。以下是脚本源文件为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # cat tcp_checker.py #!/usr/bin/env python import socket import re import sys def check_server(address, port): # Create a TCP socket s = socket.socket() print "\033[33mAttempting to connect to %s on port %s\033[0m" % (address, port) try: s.connect((address, port)) print "\033[32mConnected to %s on port %s\033[0m" % (address, port) return True except socket.error, e: print "\033[31mConnection to %s on port %s failed: %s\033[0m" % (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, default is localhost" , metavar= "ADDRESS" ) parser.add_option( "-p" , "--port" , dest= "port" , type = "int" , default=80, help= "PORT for server, default is 80" , 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) |
运行结果为:
1 2 3 4 5 | # python tcp_checker.py -a 192.168.56.108 -p 4000 options: { 'port' : 4000, 'address' : '192.168.56.108' }, args: [] Attempting to connect to 192.168.56.108 on port 4000 Connected to 192.168.56.108 on port 4000 check_server returned True |