Python Port Scanner in 3 Lines
April 17th, 2009

Just wanted to see how few lines I could do it in.  If you don’t include the ‘includes’ or the ‘except:pass’, it’s really only two lines.

#!/usr/bin/python
 
import sys
from socket import *
 
for port in range(int(sys.argv[2].split('-')[0]), int(sys.argv[2].split('-')[1])+1):
    try:socket(AF_INET, SOCK_STREAM).connect((sys.argv[1], port)); print "Able to connect to port:", port
    except: pass

Usage: <filename> <host> <ports>
So for example if you saved this as pyscanner.py, and chmod +x it, you could do:

./pyscanner.py localhost 1-1024

to scan the priviledged ports on your local box.

If it isn’t obvious from the code, it does not support IPv6 addresses and determines of a port is connectable via a standard TCP connect().