The script source file is:
# cat tcp_checker.py #!/usr/bin/env pythonimport socketimport reimport Sysdef 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,&NBsp;e) return Falseif __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)
The result of the operation is:
# python tcp_checker.py-a 192.168.56.108-p 4000options: {' Port ': 4000, ' address ': ' 192.168.56.108 '}, args: []attempting To connect to 192.168.56.108 on port 4000Connected to 192.168.56.108 on port 4000check_server returned True
This article is from the "Tiandaochouqin" blog, make sure to keep this source http://lavenliu.blog.51cto.com/5060944/1690415
TCP port check of Python script