The scanner you built works, but checks ports one at a time — and spends almost all its time waiting. This lesson fixes that with threads, then teaches the scanner to report what each open service actually is.
Why threads make scanning fast
Port scanning is I/O-bound: your CPU sits idle while the network replies. Threads let you fire off many connection attempts at once, so the waiting overlaps instead of stacking up.
import socket
from concurrent.futures import ThreadPoolExecutor
def scan(port):
s = socket.socket()
s.settimeout(1)
if s.connect_ex(('127.0.0.1', port)) == 0:
print(f'[+] {port} open')
s.close()
with ThreadPoolExecutor(max_workers=100) as pool:
pool.map(scan, range(1, 1025))
ThreadPoolExecutor runs up to 100 scans in parallel — turning a minute into a second.
Banner grabbing: ask the service who it is
Many services announce themselves the moment you connect. Reading that first reply — the banner — often reveals the software and version.
def grab_banner(host, port):
s = socket.socket()
s.settimeout(2)
s.connect((host, port))
banner = s.recv(1024).decode(errors='ignore')
s.close()
return banner.strip()
| Open port | A banner might reveal |
|---|---|
| 22 | OpenSSH 8.9 |
| 21 | vsFTPd 3.0.3 |
| 80 | The web server, e.g. nginx |
A version number is gold to an attacker — and to a defender, because it tells you exactly what needs patching.
Tip: More threads isn't always better. Push
max_workerstoo high and you'll flood your own network card or trip rate limits, making the scan slower and noisier. Start around 100 and tune from there.
From toy to tool
Scan in parallel, grab a banner on every open port, and you've rebuilt the core of Nmap's most-used features in under 40 lines — and you understand what the big tools do under the hood.