Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 149 ยท Data and the Web

Python for Cybersecurity

Learn how security professionals use Python - port scanning with sockets, packet crafting with Scapy, SSH automation with Paramiko, packet parsing and log analysis - with runnable examples.

Security teams use Python every day. It is quick to write, it has a socket library in the standard toolbox, and mature packages exist for packets, SSH, web requests and cryptography. Defenders use it to read logs, scan their own networks and automate responses; penetration testers use it to build small, custom tools.

This lesson introduces the main tools and the thinking behind them: what a port scanner does, how a packet is laid out, how to automate SSH safely, and how to spot an attack in a log file. Anything that touches a network is shown as read-only code, and everything else runs here.

Only test what you own or are explicitly allowed to test. Scanning or probing other people's systems without permission is illegal in many countries and can get your connection cut off. Practice on your own machine, a home lab, or a deliberately vulnerable training environment, and get written authorization for any work on someone else's systems.

What security tools do

Most security scripts fall into four jobs:

  • Discover: which hosts and services are reachable (scanning).
  • Observe: what is on the wire or in the logs (sniffing and log analysis).
  • Act: log in, run commands or send crafted traffic (SSH automation, packet crafting).
  • Protect: hash, encrypt and validate (see Python Security for hashing, secrets and injection).

A port scanner with sockets

A TCP port is a numbered door on a machine, and a service such as a web server listens on one (80 for HTTP, 443 for HTTPS, 22 for SSH). A port scanner tries to connect to each port and records which ones answer. With the standard socket module that is a few lines. connect_ex() returns 0 when the connection succeeds, instead of raising an exception.

Python
import socket

def scan(host: str, ports: range, timeout: float = 0.5) -> list[int]:
    open_ports = []
    for port in ports:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            sock.settimeout(timeout)               # don't wait forever on filtered ports
            if sock.connect_ex((host, port)) == 0:
                open_ports.append(port)
    return open_ports

print(scan("127.0.0.1", range(1, 1025)))           # scan only your own machine

A sequential scan of a thousand ports with a half-second timeout can take minutes when most ports are filtered. Real scanners run many probes at once with concurrent.futures.ThreadPoolExecutor, because the time is spent waiting for the network, not computing (the same reason threads help with I/O).

The program below separates the scanning logic from the network by taking the probe function as a parameter. The probe here is a fake, so it runs in your browser and shows the structure, the service-name lookup and the report:

Python Scanner logic with a simulated host

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A scanner finds open ports but says little about what runs there. The next step is banner grabbing (reading the greeting a service sends) and checking versions against known vulnerabilities, which is what tools like Nmap automate.

Packets: what is on the wire

Network data travels in packets, each starting with headers that follow a fixed binary layout. Python's struct module reads such layouts. This program builds an IPv4 header and a TCP header by hand, then parses them back and verifies the header checksum: the same work a packet sniffer does.

Python Build and parse IPv4 and TCP headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice "!" in every format string: it means network byte order (big-endian), which is how protocols write numbers. A valid header sums to zero under the checksum, so the check checksum(header) == 0 catches corruption.

Scapy: crafting and sniffing packets

Writing headers by hand teaches the layout, but the third-party Scapy library (pip install scapy) builds, sends and decodes packets for you. Layers are stacked with the / operator. Sending raw packets and sniffing need administrator (root) rights and, on Windows, a packet-capture driver such as Npcap.

Python
from scapy.all import IP, TCP, sr1, sniff

# A SYN "half-open" probe: a SYN-ACK reply means the port is open
probe = IP(dst="192.168.1.10") / TCP(dport=22, flags="S")
reply = sr1(probe, timeout=2, verbose=0)           # send, wait for one reply

if reply is not None and reply.haslayer(TCP) and reply[TCP].flags == "SA":
    print("port 22 is open")

# Capture ten web packets on the local network
sniff(filter="tcp port 80", count=10, prn=lambda packet: print(packet.summary()))

Defenders use this to test firewall rules and capture traffic for analysis. The filter is a BPF expression, the same syntax tcpdump uses.

SSH automation with Paramiko

Administrators often need to run the same command on dozens of servers. Paramiko (pip install paramiko) is a pure-Python SSH client that opens a session and runs commands remotely.

Python
import os
import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()                                 # trust hosts you already know
client.set_missing_host_key_policy(paramiko.RejectPolicy())    # refuse unknown servers

client.connect(
    "server.example.com",
    username="deploy",
    key_filename=os.path.expanduser("~/.ssh/id_ed25519"),      # key-based login, no password in code
)

stdin, stdout, stderr = client.exec_command("uptime")
print(stdout.read().decode().strip())
print("exit status:", stdout.channel.recv_exit_status())
client.close()

Two safety points. First, host key checking: AutoAddPolicy accepts any server without verification and so exposes you to man-in-the-middle attacks, which is why the example uses RejectPolicy. Second, prefer key-based authentication and never hard-code a password. The scp-style file transfer is available through client.open_sftp().

Finding attacks in logs

The defensive counterpart to a scanner is the log. A repeating pattern of failed logins from one address suggests a brute-force attack. Regular expressions pull the fields out, and a Counter totals them.

Python Detect brute-force logins in an auth log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In production you would stream a real log file instead of a string, then feed alerts to a tool that blocks the address (for example Fail2ban does exactly this) or to your monitoring system. See Logging and Warnings for writing logs of your own.

Good practice for security scripts

  • Get permission in writing before testing systems you don't own.
  • Treat input from the network as hostile: validate sizes and formats before trusting them.
  • Don't store secrets in code: use environment variables or a secrets manager.
  • Log what your tool did so an audit can reconstruct it.
  • Use ready-made, maintained tools (Nmap, Wireshark, Metasploit) for production assessments, and use your own scripts to automate, extend and understand them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does sock.connect_ex((host, port)) return when the connection succeeds?

    connect_ex returns 0 on success and an error code otherwise, instead of raising an exception like connect().
  2. 2. Why do the struct format strings for packet headers start with "!"?

    Network protocols store multi-byte numbers big-endian, and "!" tells struct to use that order.
  3. 3. Which Paramiko host-key policy is the safe choice for production code?

    Rejecting unknown host keys protects against man-in-the-middle attacks. AutoAddPolicy trusts any server.
  4. 4. Why are port scanners usually run with threads?

    The work is I/O-bound waiting, which is the case where threads help despite the GIL.
  5. 5. When is it acceptable to port-scan a system?

    Unauthorized scanning can be illegal. Test your own machines or get written authorization.

Summary

  • Security scripts discover, observe, act and protect. Python covers all four with short programs.
  • A port scanner tries TCP connections and records which ports accept them; run it only against systems you are permitted to test.
  • struct decodes binary packet headers (use "!" for network order), and Scapy crafts and sniffs packets with the / layering operator.
  • Paramiko automates SSH. Verify host keys and use keys instead of passwords.
  • Regular expressions and Counter turn raw logs into alerts such as a brute-force detector.
  • Use established tools for real assessments, and always work with authorization.

Next: What's new in Python 3.13, covering the language's newest features.