Python socket port: to detect server ports instead of Telnet

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.