Quick Python Port Scanner

1 minute read

I’m not a programmer by trade and only have limited experience by just hacking and slashing existing code to accommodate my needs for work/pen testing. In an attempt at increasing my knowledge in the area, I created a quick and simple port scanner. It’s by no means anywhere close to the functionality of nmap but it was a lot of fun making and I learned a lot during the process. I encourage you to create some scripts for anything you plan on doing more than once just for the sheer experience of it. Hit up the references at the bottom for further clarification or drop me some comments.

Python Code

This has only been tested on the Kali.

#!/usr/bin/env python
import socket, sys
from threading import Thread

# Easily changeable variables (you can extend the timeout length if necessary)
threads = []
timeout = 0.5

# Inputs & simple error handling
   host = raw_input("Enter Target Host Address: ")
   hostIP = socket.gethostbyname(host)
   startPort = int(raw_input("Enter Starting Port to Scan: "))
   endPort = int(raw_input("Enter Ending Port to Scan: "))

except KeyboardInterrupt:
    print "\n\n[*]User requested an interrupt[*]"

except socket.gaierror:
    print "\n\n[*]Hostname unresolvable[*]"

except socket.error:
    print "\n\n[*]Unable to connect to target[*]"

# Scanning Banner
print "-" * 50
print "Scanning Target: ", hostIP
print "-" * 50

# Scanning and open port display
def scanner(port):
    	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	result = sock.connect_ex((hostIP, port))
	if result == 0:
	    print "[*] Port {}: Open".format(port)

# Setup threading and calling the scan
for i in range(startPort, endPort+1):
	thread = Thread(target=scanner, args=(i,))

[x.join() for x in threads]

# Completion Banner
print "-" * 50
print "Scanning completed!"
print "-" * 50


Internal Scan
Interal Scan

External Scan
External Scan

Ctrl + C Handling
CTRLC Handling

Host Unreachable Handling
Host Unreachable


Python Socket Programming
Sploit: How to Make a Python Port Scanner
Python For Beginners