Foundations / Python for security work
Python for security work cheat sheet
Run Python and virtual environments
| Task | Code |
|---|---|
| Check the version | python3 --version |
| Run a script | python3 hello.py |
| Make a virtual environment | python3 -m venv .venv |
| Activate and leave it | source .venv/bin/activate, deactivate |
| Run with the venv interpreter | .venv/bin/python hello.py |
| Read the last exit code | echo "exit code: $?" |
Values and collections
| Task | Code |
|---|---|
| Cut a line into words | clean = line.strip(), parts = clean.split() |
| Take the text after a marker | clean.split(" from ")[1].split()[0] |
| Add to a list, slice it | attempts.append(x), attempts[1:3] |
| Count with a dictionary | failed[address] = failed.get(address, 0) + 1 |
| Count with Counter | Counter(items).most_common(), Counter(items).most_common(1) |
| Find what is not allowed | seen - allowed |
| Check an address | ipaddress.ip_address(address) |
Decisions, loops and functions
| Task | Code |
|---|---|
| Number the lines of a file | for number, line in enumerate(handle, start=1): |
| Filter into a new list | [p for p in ports if p in (80, 443)] |
| Run only as a program | if __name__ == "__main__": |
def is_noisy(count, threshold=5):
"""Return True when count reaches the threshold."""
return count >= thresholdFiles, JSON and CSV
| Task | Code |
|---|---|
| Read one line at a time | with log.open(encoding="utf-8", errors="replace") as handle: |
| Make a path object | Path("data/auth.log") |
| Write JSON | json.dumps(report, indent=2) |
| Read JSON | json.load(handle) |
| Write CSV rows | csv.DictWriter(handle, fieldnames=["address", "count"]) |
| Read CSV rows | csv.DictReader(handle) |
| Open a file that may hold bad bytes | Path("x.log").open(encoding="utf-8", errors="replace") |
| Write JSON to a file | json.dump(result, out, indent=2) |
| Open a file for CSV | open("data/failed.csv", "w", newline="", encoding="utf-8") |
Errors, logging and command line
| Task | Code |
|---|---|
| Raise a clear error | raise ValueError(f"port out of range: {port}") |
| Log with lazy formatting | log.info("read %s", path) |
| Set up logging once | logging.basicConfig(level=logging.INFO) |
| Add an argument | parser.add_argument("--max", type=int, default=3) |
| Add a switch with no value | parser.add_argument("-v", action="store_true") |
| Return an exit code | sys.exit(main()) |
| Exit codes of the course tools | 0 clean, 1 finding, 2 bad usage, 3 file error |
try:
failed = count_failed(args.logfile)
except OSError as error:
log.error("cannot read %s: %s", args.logfile, error.strerror)
return 3HTTP and APIs
| Task | Code |
|---|---|
| Make a random key | secrets.token_hex(8) |
| Put a key in the environment | export KR_API_KEY=$(python3 -c "import secrets; print(secrets.token_hex(8))") |
| Start the server in the background | python3 api.py 2> api.log & |
| List the background jobs, stop job 1 | jobs, kill %1 |
| Remove the key again | unset KR_API_KEY |
| Read a key from the environment | os.environ.get("KR_API_KEY") |
| Build a request | urllib.request.Request(BASE + path, headers={"Accept": "application/json"}) |
| Add a header | request.add_header("X-Api-Key", key) |
| Call with a timeout | urllib.request.urlopen(request, timeout=timeout) |
| Catch a 4xx or 5xx | except urllib.error.HTTPError as error: |
| Catch a refused connection | except urllib.error.URLError as error: |
Packages and the supply chain
| Task | Code |
|---|---|
| Show installed packages | pip list, pip show requests |
| Pin versions | pip freeze > requirements.txt |
| Rebuild from the file | pip install -r requirements.txt |
| Check for broken requirements | pip check |
| Download a wheel only | pip download --only-binary=:all: --no-deps -d wheels idna==3.20 |
| Get a file hash | pip hash wheels/idna-3.20-py3-none-any.whl |
| Refuse unhashed files | pip install --require-hashes -r requirements-hashed.txt |
| Hash a file in Python | hashlib.sha256(Path(f).read_bytes()).hexdigest() |
| Hash a file in the shell | sha256sum file |
| Find a name that copies another | difflib.get_close_matches(name, KNOWN, n=1, cutoff=0.8) |
| List a wheel's files | python3 -m zipfile -l wheels/requests-2.34.2-py3-none-any.whl |
Time, tests and other programs
| Task | Code |
|---|---|
| Read a log time (add the year) | datetime.strptime(f"2026 {stamp}", "%Y %b %d %H:%M:%S") |
| Make a time aware in UTC | local.replace(tzinfo=zone).astimezone(timezone.utc) |
| A fixed zone one hour ahead | timezone(timedelta(hours=1)) |
| Is a gap inside the window? | later - earlier <= timedelta(minutes=5) |
| Test a function | self.assertEqual(burst([], FIVE, 3), {}) in a unittest.TestCase |
| Run the tests | python3 -m unittest -v test_burst |
| Run a program safely | subprocess.run(["sha256sum", path], capture_output=True, text=True, timeout=10, check=True) |
| Read its exit code and output | done.returncode, done.stdout, done.stderr |
Regular expressions
| Task | Code |
|---|---|
| Prepare a pattern | FAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+)") |
| Search a line | match = FAILED.search(line) |
| Take the kept parts | user, address = match.groups() |
| Parts of a pattern | \S not a space, \d digit, + one or more, ? optional, ( ) keep, (?: ) do not keep, ^ $ line start and end |
Safety habits
- Never run
sudo pip install. Use a virtual environment. - Treat every log field as attacker data. Never pass it to a shell.
- Set a timeout on every network call. Never turn off TLS checks.
- Keep keys out of source code. Read them from the environment.
- Pin versions and hashes. Compare package names letter by letter.
- Return a non-zero exit code on failure.
- Store and compare times in UTC. Give every time a zone.
- Run another program with a list of words and a timeout, never
shell=True. - Write a failing test for a bug before you fix it.
- Remove a key from the shell when you finish:
unset KR_API_KEY.