Scene:
In the use of Linux process, we often use Telnet to test the other server a port is open, but Linux is not installed by default Telnet client, many times the temporary installation of Telnet will be more troublesome, this time can be used in Python to do a simple test.
Pythonimport Sockets=socket.socket () s.connect (("IP", port) s.close
Note: The socket module is actually called, and Telnet is the only way to test the TCP port.
Script:
1 #!/usr/bin/python 2 3 import socket,re,sys 4 5 def check_server (Address,port): 6 s=socket.socket () 7 print "Attempting to connect to %s on port %s " % (address,port) 8 9 try: 10 s.connect ((address,port)) 11 print "Connected" 12 return true 13 except socket.error,e: 14 print "Failed" 15 return False 16 17 if __name__ == ' __main__ ': 18 from optparse import optionparser 19 parser=optionparser () 20 21 parser.add_option ("-A","--address ", dest=" address ", default= ' localhost ', help=" address for server ", metavar=" ADDRESS ") 22 parser.add_option ("-P ","--port ", dest=" Port ", type=" int ", default=80,help=" Port for server ", metavar=" PORT ") 23 24 (Options,args) =parser.parse_args () 25 print ' options %s ,args %s '% (Options,args) 26 print options.address,options.port 27 check=check_server (Options.address,options.port) 28 29 print ' check_server returned %s ' %check 30 sys.exit (not Check) ~
This article is from the "Hiubuntu" blog, make sure to keep this source http://qujunorz.blog.51cto.com/6378776/1546083
Python socket port: to detect server ports instead of Telnet