ProgrammingDemonstration content

Building Your First Python Security Tool

Writing a simple port scanner with socket and argparse — a small project that teaches concurrency, error handling, and the ethics of testing.

Building Your First Python Security Tool
Table of contents

The fastest way to understand a security technique is to build the tool yourself. In this article we build a small port scanner in Python — not to replace Nmap, but to understand what such a tool actually does.

Use this tool only on networks and hosts you own or have written permission to test. Scanning systems without authorization is illegal in many jurisdictions.

Design

The scanner will:

  1. Take a target and a port list from CLI arguments.
  2. Attempt a TCP connection to each port.
  3. Report the open ports.

The simplest version uses the built-in socket module:

import argparse
import socket

def scan_port(host: str, port: int, timeout: float = 1.0) -> bool:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.settimeout(timeout)
        return sock.connect_ex((host, port)) == 0

def main() -> None:
    parser = argparse.ArgumentParser(description="Simple TCP port scanner")
    parser.add_argument("host")
    parser.add_argument("--ports", default="1-1024")
    parser.add_argument("--timeout", type=float, default=1.0)
    args = parser.parse_args()

    start, end = (int(p) for p in args.ports.split("-"))
    for port in range(start, end + 1):
        if scan_port(args.host, port, args.timeout):
            print(f"[open] {args.host}:{port}")

if __name__ == "__main__":
    main()

Problem: the sequential version is too slow

One port with a 1-second timeout means scanning 1000 ports can take up to 17 minutes on a host that drops everything. The fix is concurrency — in modern Python, ThreadPoolExecutor is enough and easy to read:

from concurrent.futures import ThreadPoolExecutor, as_completed

def scan_ports(host: str, ports: range, timeout: float) -> None:
    with ThreadPoolExecutor(max_workers=100) as pool:
        futures = {
            pool.submit(scan_port, host, port, timeout): port
            for port in ports
        }
        for future in as_completed(futures):
            port = futures[future]
            if future.result():
                print(f"[open] {host}:{port}")

With 100 parallel workers, a 1000-port scan finishes in seconds.

Input validation

A tool that accepts user input should reject nonsense — the same lesson as in web application security:

import ipaddress

def resolve_target(target: str) -> str:
    try:
        ipaddress.ip_address(target)
        return target
    except ValueError:
        return socket.gethostbyname(target)

Limitations of this version

A simple TCP connect scanner has limitations worth understanding:

  • Noisy — full connections show up in the target’s logs, unlike SYN scans.
  • No service detection — we know the port is open, not what runs there.
  • Firewalls — a host dropping packets looks “closed” when it may simply be filtered.

This is why tools like Nmap implement dozens of scanning techniques, and why understanding the protocol underneath is worth more than memorizing flags.

Ideas to extend it

A few directions to keep learning:

  1. Add banner grabbing: read the first bytes from open ports.
  2. Save results to JSON so scans can be compared over time.
  3. Add a --rate option to throttle the scan speed.
Share
Tags