Build a Port Scanner and Banner Grabber in Python
Use sockets, timeouts, thread pools, rate limiting, and banner grabbing to build a lab-only TCP scanner that writes reproducible JSON and CSV output.
By the end, you’ll be able to…
- Explain what a TCP connect scan proves and what it cannot tell you.
- Use Python sockets, timeouts, and error codes to probe ports safely.
- Add bounded concurrency and a shared rate limiter with ThreadPoolExecutor.
- Grab service banners and produce deterministic JSON and CSV reports with clear error handling.
01A Port Scanner Is a Map, Not a Verdict
A port scanner answers a narrow question: which TCP ports on a host accept a connection? That is useful for inventory, change detection, and authorized testing. It is not a vulnerability scanner. An open port tells you that something is listening, not what version it runs, whether it is patched, or whether it is safe. Treat the result as a lead, then verify the service through its own protocol and configuration.
A TCP connect scan completes the normal three-way handshake. It works without raw sockets or root privileges, which makes it portable and easy to understand. The trade-off is noise: the service and any firewall or monitoring system can log the connection. A SYN scan is quieter but needs raw sockets; it is a different tool for a different job. In this lesson you build the connect scan, because understanding the handshake matters more than hiding from it.
Authorization comes before code. Scan only a lab virtual machine, localhost, or a system for which you have written permission. Scanning addresses you do not own can violate law, cloud terms, and network policy, even if the scan is brief. Keep the rate low, announce the test window, and stop if you see unexpected instability. A scanner is not a license to explore.
02Sockets, Timeouts, and the Connect Scan
Python's socket module exposes the operating system's network API. A stream socket uses AF_INET for IPv4 and SOCK_STREAM for TCP. connect_ex attempts a connection and returns an error code instead of raising for the common refusal case, which makes it convenient for scanning. Set a timeout so a filtered port cannot hang a worker forever, and close every socket with a context manager.
A successful connect means the handshake completed. A refused connection usually means the host is reachable but nothing is listening. A timeout may mean a firewall dropped the packet, the host is down, or the network is slow. The connect scan cannot reliably tell filtered from closed in every case, so label timeouts as filtered or unknown rather than pretending to know. Record the error code for debugging.
Do not resolve the hostname for every port. Resolve once, validate the address, and reuse it. Handle name-resolution errors before starting the pool. Watch file-descriptor and ephemeral-port limits if you raise concurrency. Sequential scans are simple but slow; concurrency is the next step, and it must be bounded.
03Concurrency Without Chaos
Most of a scanner's time is spent waiting for the network. Threads are a good fit for this I/O-bound work: while one worker waits for a timeout, another can attempt a connection. ThreadPoolExecutor gives you a fixed pool and a future for each task. Collect results in the main thread with as_completed so the output is not mutated from many threads at once.
Bound the pool. Creating one thread per port looks simple until you scan 65,535 ports and exhaust memory or file descriptors. A pool of 20 to 100 workers is plenty for a lab. Bound the queue as well if the port list is huge, and handle Ctrl-C so the program exits without leaving threads running. Deterministic output matters: sort by port before writing JSON or CSV.
Rate limiting is both polite and protective. A token-bucket limiter with a lock lets all workers share one connection budget. Without it, a high worker count can flood a small service or trigger an intrusion-prevention system. Add a small delay or lower the rate when you see timeouts, and never scan a shared network at full speed. The goal is evidence, not maximum packets per second.
04Banner Grabbing and Service Hints
A banner is text a service sends when a client connects, or text it returns after a protocol-specific request. SSH servers usually announce their version immediately. HTTP servers wait for a request, so send a minimal HEAD request. TLS services expect a handshake, so use Python's ssl module rather than reading raw bytes and hoping. Banner grabbing is protocol work, not magic.
Treat every banner as untrusted input. It can be absent, truncated, deliberately misleading, or full of control characters. Decode with errors='replace', collapse whitespace, limit the length, and never render raw escape sequences to a terminal. A banner may reveal a product and version, which is a hint for inventory, not proof of a vulnerability. Confirm with the service's own protocol and an authorised vulnerability check.
Map well-known ports to service names for readability, but keep the raw port number. Services move, proxies listen on unexpected ports, and a label can be wrong. For TLS, record the negotiated protocol version and certificate subject only if your lab trust store is configured. Do not send exploit payloads, brute-force credentials, or attempt authentication. The scanner observes; it does not attack.
05The Complete Scanner
The complete example combines the pieces: argument parsing, a port specification parser, a bounded thread pool, a shared rate limiter, optional banner grabbing, and JSON or CSV output. It resolves the host once, validates the port range, writes progress to stderr, and returns a non-zero exit code for invalid input. Read it from top to bottom before running it.
Keep the data model explicit. Each result records the host, port, state, service hint, banner, and error. Errors are evidence: a timeout, a refused connection, and a name-resolution failure mean different things. Writing them to JSON makes the scan reproducible and lets another analyst review what happened without re-running it. CSV is convenient for a spreadsheet; JSON is better for automation.
Run the scanner against localhost or a lab VM with a known set of services. Compare the result with ss -tulpn on the target. Try a closed port, a filtered port, and a service that sends no banner. Then compare JSON and CSV output. The tool is finished when its behaviour is predictable, not when it produces a long list of open ports.
06Reading Results and Staying Legal
Read results in context. A new management port, a database reachable from the workstation network, or an unexpected development service matters more than a hundred expected web ports. Compare against a baseline and ask who owns each service. Confirm the listening process on the host, then check the firewall path from the client. A port visible from one network may be invisible from another.
Write a short report: scope and authorization, target, time window, method, rate, ports scanned, results, and limitations. State that the scan was a TCP connect scan and that filtered ports are ambiguous. Do not publish scans of third-party systems. If you find a serious exposure in an authorized test, report it through the agreed channel instead of exploiting it.
Use the scanner to improve defense. Turn unexpected open ports into tickets, add them to monitoring, and verify that firewall rules match intent. On the defensive side, alert on bursts of connection attempts and on new listeners. The same evidence that helps an attacker map a host helps a defender notice drift.
The ideas worth keeping.
- A TCP connect scan maps reachable listeners; it does not prove vulnerability or service health.
- Authorisation, a low rate, and a bounded worker pool are part of the tool's design.
- Banner grabbing is protocol-specific and its output is untrusted input.
- Deterministic JSON and CSV output with error fields makes a scan reproducible and reviewable.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Add an authorization guard
Modify the scanner so it refuses to run against public IP addresses unless the operator passes an explicit --allow-public flag. Add a --dry-run mode that prints what would be scanned without opening a socket. Explain why these controls are useful even in a personal lab.
Explore a worked solution
Use the ipaddress module. Resolve the host once with socket.getaddrinfo, convert each result to ipaddress.ip_address, and reject any address that is not private, loopback, or link-local unless --allow-public is present. Print a clear error and exit with status 2. For --dry-run, build the port list, print the target, port count, worker count, rate, and output paths, then return without creating the pool. Add a test that a public documentation address is rejected by default and one that a private lab address is accepted. The guard prevents a typo or a copied command from turning a lab exercise into unauthorized scanning, and the dry run makes the scope reviewable before any packet is sent.Safety controls belong in the tool, not only in the operator's memory. A default-deny target policy and a reversible dry run reduce the chance of an accidental scan of someone else's network.
Exercise 2: Test the port parser and rate limiter
Write unit tests for parse_ports and RateLimiter. Cover a single port, a range, a mixed list, an invalid range, an out-of-bounds port, and a zero rate. Explain which tests are deterministic and which depend on timing.
Explore a worked solution
Use unittest. For parse_ports, assert that '22' returns [22], '22,80,443' returns the sorted list, '1-3' returns [1, 2, 3], '9-4' raises ValueError, '0,70000' raises ValueError, and an empty string raises ValueError. For RateLimiter, test that a zero rate returns immediately and that two waits with a small rate take at least the expected interval within a generous tolerance. Keep timing assertions loose, or inject a fake clock into the limiter so the test does not depend on the scheduler. Run the suite with python -m unittest -v. Parsing tests are deterministic; rate tests can be flaky unless the clock is abstracted.Input parsing should be tested without network access. Timing behaviour needs either a tolerance or a fake clock; otherwise a busy CI machine will produce false failures.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.