Python Port Scanner
March 29, 2008
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.
download?
Comment by guest — March 31, 2008 @ 2:11 am
I didn’t upload the file because I thought it would be easy enough to just copy and paste. Click on the copy to clipboard button and then paste it into notepad, and save as scanner.py.
If you’d still find it useful for me to upload the file let me know.
Comment by admin — March 31, 2008 @ 7:35 am
Excellent program!! Quick and easy to write and an excellent start to my current project, a set of python based network security tools with a GUI interface…
Thanks!
Comment by Zachary D. Skelton — June 24, 2008 @ 3:22 am
This is a great way to show people the basics of port scanning. But not too practical.
Threading would cut the time radically. And maybe wrap it into a class. Just a thought though.
Good job.
Comment by Tech B. — January 14, 2010 @ 1:18 am
How would one handle the threading aspect? When I have worked with counters and threads before, I always get different threads acccessing the same number i.e.:
counter = 0
(code goes here)
counter += 1
threads dont behave good for me. Any ideas or links?
Comment by AJ Atkinson — May 16, 2010 @ 5:47 pm
@AJ Atkinson: In your example you’d either need an atomic increment commend or you’d have to make sure that only one thread updates the counter at a time, by using a lock.
See http://en.wikipedia.org/wiki/Mutual_exclusion for an overview of mutual exclusion, and the following Python documentation for details of locks: http://docs.python.org/library/thread.html
Comment by Ben — May 20, 2010 @ 3:17 pm
Ready to run multi threaded with locks
http://code.activestate.com/recipes/286240-python-portscanners/
Comment by Denis — June 18, 2010 @ 7:22 pm