Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Foundations / Python for security work

Python for security work cheat sheet

Run Python and virtual environments

TaskCode
Check the versionpython3 --version
Run a scriptpython3 hello.py
Make a virtual environmentpython3 -m venv .venv
Activate and leave itsource .venv/bin/activate, deactivate
Run with the venv interpreter.venv/bin/python hello.py
Read the last exit codeecho "exit code: $?"

Values and collections

TaskCode
Cut a line into wordsclean = line.strip(), parts = clean.split()
Take the text after a markerclean.split(" from ")[1].split()[0]
Add to a list, slice itattempts.append(x), attempts[1:3]
Count with a dictionaryfailed[address] = failed.get(address, 0) + 1
Count with CounterCounter(items).most_common(), Counter(items).most_common(1)
Find what is not allowedseen - allowed
Check an addressipaddress.ip_address(address)

Decisions, loops and functions

TaskCode
Number the lines of a filefor 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 programif __name__ == "__main__":
def is_noisy(count, threshold=5):
    """Return True when count reaches the threshold."""
    return count >= threshold

Files, JSON and CSV

TaskCode
Read one line at a timewith log.open(encoding="utf-8", errors="replace") as handle:
Make a path objectPath("data/auth.log")
Write JSONjson.dumps(report, indent=2)
Read JSONjson.load(handle)
Write CSV rowscsv.DictWriter(handle, fieldnames=["address", "count"])
Read CSV rowscsv.DictReader(handle)
Open a file that may hold bad bytesPath("x.log").open(encoding="utf-8", errors="replace")
Write JSON to a filejson.dump(result, out, indent=2)
Open a file for CSVopen("data/failed.csv", "w", newline="", encoding="utf-8")

Errors, logging and command line

TaskCode
Raise a clear errorraise ValueError(f"port out of range: {port}")
Log with lazy formattinglog.info("read %s", path)
Set up logging oncelogging.basicConfig(level=logging.INFO)
Add an argumentparser.add_argument("--max", type=int, default=3)
Add a switch with no valueparser.add_argument("-v", action="store_true")
Return an exit codesys.exit(main())
Exit codes of the course tools0 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 3

HTTP and APIs

TaskCode
Make a random keysecrets.token_hex(8)
Put a key in the environmentexport KR_API_KEY=$(python3 -c "import secrets; print(secrets.token_hex(8))")
Start the server in the backgroundpython3 api.py 2> api.log &
List the background jobs, stop job 1jobs, kill %1
Remove the key againunset KR_API_KEY
Read a key from the environmentos.environ.get("KR_API_KEY")
Build a requesturllib.request.Request(BASE + path, headers={"Accept": "application/json"})
Add a headerrequest.add_header("X-Api-Key", key)
Call with a timeouturllib.request.urlopen(request, timeout=timeout)
Catch a 4xx or 5xxexcept urllib.error.HTTPError as error:
Catch a refused connectionexcept urllib.error.URLError as error:

Packages and the supply chain

TaskCode
Show installed packagespip list, pip show requests
Pin versionspip freeze > requirements.txt
Rebuild from the filepip install -r requirements.txt
Check for broken requirementspip check
Download a wheel onlypip download --only-binary=:all: --no-deps -d wheels idna==3.20
Get a file hashpip hash wheels/idna-3.20-py3-none-any.whl
Refuse unhashed filespip install --require-hashes -r requirements-hashed.txt
Hash a file in Pythonhashlib.sha256(Path(f).read_bytes()).hexdigest()
Hash a file in the shellsha256sum file
Find a name that copies anotherdifflib.get_close_matches(name, KNOWN, n=1, cutoff=0.8)
List a wheel's filespython3 -m zipfile -l wheels/requests-2.34.2-py3-none-any.whl

Time, tests and other programs

TaskCode
Read a log time (add the year)datetime.strptime(f"2026 {stamp}", "%Y %b %d %H:%M:%S")
Make a time aware in UTClocal.replace(tzinfo=zone).astimezone(timezone.utc)
A fixed zone one hour aheadtimezone(timedelta(hours=1))
Is a gap inside the window?later - earlier <= timedelta(minutes=5)
Test a functionself.assertEqual(burst([], FIVE, 3), {}) in a unittest.TestCase
Run the testspython3 -m unittest -v test_burst
Run a program safelysubprocess.run(["sha256sum", path], capture_output=True, text=True, timeout=10, check=True)
Read its exit code and outputdone.returncode, done.stdout, done.stderr

Regular expressions

TaskCode
Prepare a patternFAILED = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+)")
Search a linematch = FAILED.search(line)
Take the kept partsuser, 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