04 security

This is why most of us learned Python in the first place The standard library does the boring parts , you supply the judgement

Table of Contents

HTTP requests

The example below was syntax checked , the network call itself was not run during verification

import requests

try:
    response = requests.get("https://example.com", timeout=5)
    response.raise_for_status()
    print(f"Status Code: {response.status_code}")

    headers = {"User-Agent": "MyScanner/1.0"}
    params = {"id": "123"}
    response = requests.get("https://httpbin.org/get", headers=headers, params=params, timeout=5)

    payload = {"username": "admin", "password": "password123"}
    response = requests.post("https://httpbin.org/post", data=payload, timeout=5)
    print(response.json())
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

A timeout is not optional Without one your script hangs forever on a host that never answers

HTML parsing

The beautifulsoup4 parser is used below Same rule , no live fetch during verification

import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url, timeout=5)
soup = BeautifulSoup(response.text, "html.parser")

print(f"Page Title: {soup.title.string}")

for link in soup.find_all("a"):
    href = link.get("href")
    if href:
        print(href)

soup.title can be None on a page without a title Check it before calling .string if the target is not yours

Sockets

The built in socket module is enough for banner grabs

import socket

def grab_banner(ip, port):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(2)
            s.connect((ip, port))
            banner = s.recv(1024)
            return banner.decode(errors="replace").strip()
    except (socket.timeout, ConnectionRefusedError, OSError) as e:
        return f"Error: {e}"

print(grab_banner("127.0.0.1", 22))

settimeout(2) is the difference between a scan and a hang errors="replace" stops a weird banner from killing your decoder

Subprocess

Use a list , never a shell string

import subprocess

def run_command(command):
    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True, timeout=30)
        return result.stdout
    except FileNotFoundError:
        return "Command not installed or not in PATH"
    except subprocess.CalledProcessError as e:
        return f"Failed with exit code {e.returncode}: {e.stderr}"
    except subprocess.TimeoutExpired:
        return "Command timed out"

print(run_command(["python3", "-c", "print('ok')"]))

check=True raises on a non zero exit timeout stops a runaway process capture_output=True keeps stdout off your terminal until you decide to print it

Regex

The old cheat sheet had a log line with nested single quotes It could not run

import re

log_line = "[2025-10-26 10:00:00] INFO: User 'admin' logged in from 192.168.1.101"
match = re.search(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", log_line)
if match:
    print(f"Found IP: {match.group(1)}")

That regex checks shape , not validity 999.999.999.999 matches For real IP validation use ipaddress.ip_address()

Unsafe deserialization

pickle.loads() runs code hidden inside the data That is not a bug you patch with a filter , it is the design

import json

# safe , data only
settings = json.loads('{"port": 443}')

# unsafe , never load pickle from a source you do not control
# pickle.loads(blob)

No weaponized payload here If you need to study that attack, do it in a lab with authorized targets and record every step

Command injection

The rule is simple: do not pass user input into a shell string

import os
import subprocess

user_input = "example.com; echo injected"

# broken , the shell sees two commands
# os.system(f"ping -c 1 {user_input}")

# safe , no shell , one argument
subprocess.run(["ping", "-c", "1", user_input], timeout=10)

os.system hands the whole string to a shell A list keeps each argument separate

Web app claims

Some tutorials say “SQL injection? Not happening” with an ORM That is misleading and it stays misleading no matter how many times it is repeated

ORMs parameterize queries when you use the ORM Write raw string concatenation and the protection disappears Template engines escape by default when you keep values in the template context Mark a value safe yourself and you opt out

Frameworks reduce the number of ways to get hurt They do not make the question stupid

Secrets

import os

api_key = os.getenv("MY_API_KEY")
if not api_key:
    raise SystemExit("MY_API_KEY is not set")

Environment variables for local work A real secrets manager for production No key in source , ever

Posted