Like the whois shell script I posted recently the Python port scanner below is another script I've had lying around on my computer for while. I wrote it when I was first learning Python and its socket API.
#!/usr/bin/env python
from socket import *
if __name__ == '__main__':
target = raw_input('Enter host to scan: ')
targetIP = gethostbyname(target)
print 'Starting scan on host ', targetIP
#scan reserved ports
for i in range(20, 1025):
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i))
if(result == 0) :
print 'Port %d: OPEN' % (i,)
s.close()
Example usage:
~$ ./scanner.py
Enter host to scan: localhost
Starting scan on host 127.0.0.1
Port 22: OPEN
Port 80: OPEN
Port 139: OPEN
Port 445: OPEN
Port 631: OPEN
The code could easily be extended to allow the user to specify what ports to scan, or to take the hostname as a command line argument.