Check open ports with Python

Everyonce in a while I run into problems testing new setups just to find out that a certain port just isn’t reachable from within our company network. This simple tool should make it easier to find open ports for quick testing.

Note it’s not the fastest tool for huge numbers of ports (e.g. 1-65535) but it’s capable of rather quickly showing open ports in 1-1024 like ranges.

Without further ado, here it is.

from multiprocessing import Process, Pool
import subprocess, sys, socket

if len(sys.argv) < 2 or sys.argv[1] == "help" or sys.argv[1] == "-h":
  print '''Usage: sslcheck.py file
  <port>: specify the port to check
  <port>: if a second port if given, script will check port-port range
  <help>: print this help text
  '''

else:
  def checkopenport(port):
    # Check Hosts for open ports
    try:
      #print "DEBUG: Testing port %i" % (port)
      p = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      p.settimeout(5)
      returncode = p.connect_ex(("portquiz.net",port))
      if returncode == 0:
        print "Open: %d" % (port)
      else:
        print "Closed %d" % (port)
    except Exception, e:
      print "Something went bad... Exception: %d %s" % (port, e)

  firstport = int(sys.argv[1])
  ports = []

  if len(sys.argv) > 2:
    lastport = int(sys.argv[2])
    portrange = (lastport - firstport) + 1
    if portrange < 1:
      print "error, no ports found"
    else:
      print "portrange is %i" % (portrange)
      pool = Pool(processes=portrange)
      for port in xrange(firstport,lastport+1):
        ports.append(port)
  else:
    # Only set the first port if no second port is given
    ports.append(firstport)
    pool = Pool(processes=1)

  # Run the threads
  results = pool.map(checkopenport, ports)