'Python Port Scanner, User Input

Working on a simple port scanner that allows user to input an IP address as well as a set of ports to scan through ie a lower boundary port and an upper boundary port inclusive, the program should scan through every port within these boundaries.

#!/usr/bin/env python

import sys
import ssl      #secure shell layer
import socket

try:
  ip = sys.argv[1]
  lowport = int(sys.argv[2])
  upport = int(sys.argv[3])
except:
  print 'you did it wrong'
  sys.exit()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10.0)

def scan(port):
  try:
    s.connect((ip, port))
    return True
  except:
    return False
  s.close()

for x in range(lowport,upport+1):
  if scan(x):
    print "Port {} open" .format(x)

however, my output seems suspect. The following are the reported open ports on three different runs.

Port 7250 open
Port 7251 open
Port 22 open
Port 23 open
Port 5004 open
Port 5005 open

I suspect my issue may be in my def scan() block though I cannot seem to figure out what I am doing wrong here. If I am able to connect to a socket, that means the port is open right? working in Python 2.7



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source