What you'll learn
- Set up an isolated, reproducible Python project
- Choose the right data structure for the job
- Parse large logs and call APIs with timeouts, retries and pagination
- Test a script with pytest and handle errors deliberately
- Replace dangerous calls with safe alternatives
Each lesson is tagged Junior, Mid or Expert, so you can start where you are. Finish with the lab and the quiz; a score of 4 out of 5 marks the course complete in this browser.
The lessons below are in English for now, because they quote technical names, commands and log fields. An Arabic version is planned.
Course map
Each module moves from fundamentals to applied work to an expert challenge. Exercises have worked solutions: try first, then open the solution. 12 modules · 24 exercises · ~3.9 hours
- 0Start here: Python, installation and the course projectJuniorMidExpert20 min · 0 exercises
- 1Values, types, operators and inputJuniorMidExpert20 min · 3 exercises
- 2Strings: indexing, slicing, methods and formattingJuniorMidExpert15 min · 2 exercises
- 3Control flow: decisions and loopsJuniorMidExpert25 min · 4 exercises
- 4Collections: lists, tuples, dictionaries and setsJuniorMidExpert25 min · 4 exercises
- 5Functions and modulesJuniorMidExpert20 min · 1 exercises
- 6Files, paths and regular expressionsJuniorMidExpert25 min · 2 exercises
- 7Errors, command-line arguments and running programsJuniorMidExpert20 min · 2 exercises
- 8Data formats and web APIsJuniorMidExpert20 min · 2 exercises
- 9Modelling data with classesJuniorMidExpert15 min · 1 exercises
- 10Packages and automated testingJuniorMidExpert20 min · 1 exercises
- 11Cheat sheet, assessment and expert challengeJuniorMidExpert10 min · 2 exercises
No prior experience is needed. Module 0 covers the architecture, installation and configuration, and sets up the project you extend in every module. Each command is labelled with its impact (read-only, changes files, changes the system, uses the network). Work on a computer or virtual machine you control.
Start here: Python, installation and the course project
Goal: Understand how Python runs a program, install the tools, read your first script, and set up the project.
Python and the interpreter
Python is a general-purpose, interpreted programming language with a readable syntax and a large standard library. Source code lives in .py files; the interpreter (python3) compiles it to bytecode in memory and executes it, so there is no separate build step.
Security and operations work is full of repeatable tasks: read logs, extract IP addresses, check them against threat intelligence, write a report. A short Python program performs them in seconds, identically every time, and leaves a record of exactly what was done. Python is also the dominant language for security tooling and AI engineering.
Running python3 file.py starts the interpreter, which executes statements from top to bottom. The standard library ships with Python (files, JSON, regular expressions, HTTP); third-party packages are installed per project when needed.
Quick check: What happens when you run python3 scan.py?
CPython compiles to bytecode in memory (cached as .pyc for imported modules) and runs it immediately.
| Symptom | Likely cause | Fix |
|---|---|---|
| 'python3: command not found' | Python not installed or not on the PATH | follow the next lesson; on Windows use py instead of python3 |
Install Python and an editor
You need Python 3.12 or newer, a terminal, and a code editor. This course uses Visual Studio Code (free); any editor works.
The course uses syntax added in recent releases (structural pattern matching, built-in generic types such as list[str]). An editor with the Python extension adds syntax checking, type hints and an integrated debugger.
Install from the Microsoft Store (search 'Python 3.13') or from python.org; on python.org tick Add python.exe to PATH. Open Windows Terminal. On Windows the command is often py; wherever this course says python3, type py.
brew install python@3.13
python3 --versionWithout Homebrew, use the installer from python.org.
sudo apt update && sudo apt install -y python3 python3-venv
python3 --versionThen install VS Code from code.visualstudio.com and its Python extension.
python3Run Python: a file, a one-liner, or the interactive prompt.Read-onlypython3 [file.py | -c 'code' | -m module]file.py | run a program file |
-c 'code' | run one line |
(nothing) | open the interactive prompt (REPL); leave with exit() |
--version | print the version |
python3 --version
python3 -c 'print(2 ** 10)'Python 3.13.18 1024
Any 3.12 or newer version is fine.
Open the interactive prompt by typing python3. At the >>> prompt type 7 * 6 and press Enter, then exit(). The prompt evaluates one statement at a time and shows the value of expressions, which makes it the fastest way to test a single line.
>>> 7 * 6 42
| Symptom | Likely cause | Fix |
|---|---|---|
| Windows opens the Microsoft Store when typing python | an app alias is active | install Python, or use py |
| version 3.8 or older | an old system Python is first on the PATH | install a current one and run it explicitly, for example python3.13 |
Reading a Python script
Before writing code, learn to read it. Every Python program is built from the same few elements: comments, variables, values, expressions, keywords, indented blocks and function calls.
Most of your early work will be reading and adapting existing scripts. Knowing what each part of a line is called lets you search for it, read error messages, and understand documentation.
Hover over or tap a callout to highlight the part of the code it describes. The same colours are used for the same concepts throughout the course: blue for variables, purple for text values, green for structure, red for function calls.
#. Ignored by Python; written for people.=. Later lines use the name to refer to the value.in tests whether one string contains another.# scan.py: flag one log line
line = "Failed password for root"
if "Failed" in line:
print("ALERT:", line)print runs with two arguments, separated by a comma, and writes them to the screen.if. The colon at the end of the if line opens the block.ALERT: Failed password for root
Quick check: Which part decides whether line 4 runs?
The indented line runs only when the condition after if evaluates to True.
The course project: iocscan
You will build iocscan, a tool that reads Rimal Logistics' server logs, finds IP addresses involved in attacks, enriches them with threat intelligence, and writes reports. IOC means indicator of compromise: evidence such as an attacker's IP address.
Each module adds one capability to the same codebase, so every concept is applied in context and the final result is a usable tool rather than a set of disconnected snippets.
Step 0 creates the folder ~/py-lab with two log files and a small threat-intelligence file. Paste the block into your terminal. It is itself a Python program; by module 6 you will understand every line.
mkdir -p ~/py-lab && cd ~/py-lab
python3 - <<'PY'
from pathlib import Path
Path("auth.log").write_text("""\
Dec 3 08:01:12 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec 3 08:01:15 web01 sshd[1201]: Failed password for root from 203.0.113.5 port 52144 ssh2
Dec 3 08:02:40 web01 sshd[1210]: Accepted publickey for deploy from 198.51.100.7 port 40022 ssh2
Dec 3 08:05:03 web01 sshd[1222]: Failed password for invalid user admin from 192.0.2.44 port 61001 ssh2
Dec 3 08:05:09 web01 sshd[1222]: Failed password for invalid user oracle from 192.0.2.44 port 61001 ssh2
Dec 3 08:07:30 web01 sudo: deploy : TTY=pts/0 ; PWD=/home/deploy ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx
Dec 3 08:09:51 web01 sshd[1240]: Failed password for root from 203.0.113.5 port 52190 ssh2
Dec 3 08:12:02 web01 sshd[1251]: Accepted password for rana from 198.51.100.23 port 50311 ssh2
""")
Path("access.log").write_text("""\
198.51.100.7 - - [03/Dec/2026:08:00:01 +0300] "GET / HTTP/1.1" 200 5120
203.0.113.5 - - [03/Dec/2026:08:00:03 +0300] "GET /wp-login.php HTTP/1.1" 404 162
203.0.113.5 - - [03/Dec/2026:08:00:04 +0300] "GET /.env HTTP/1.1" 404 162
198.51.100.23 - - [03/Dec/2026:08:01:10 +0300] "POST /api/login HTTP/1.1" 200 88
192.0.2.44 - - [03/Dec/2026:08:02:00 +0300] "GET /admin HTTP/1.1" 403 199
198.51.100.7 - - [03/Dec/2026:08:02:30 +0300] "GET /api/orders HTTP/1.1" 500 47
198.51.100.7 - - [03/Dec/2026:08:02:31 +0300] "GET /api/orders HTTP/1.1" 500 47
""")
Path("api").mkdir(exist_ok=True)
Path("api/intel.json").write_text("""{"items": [
{"ip": "203.0.113.5", "verdict": "malicious", "tags": ["ssh-bruteforce"]},
{"ip": "192.0.2.44", "verdict": "suspicious", "tags": ["scanner"]}], "next": null}""")
print("lab ready")
PYlab ready
The folder contains auth.log, access.log and api/intel.json (check with ls or the VS Code explorer). Run every later example from inside ~/py-lab.
| Symptom | Likely cause | Fix |
|---|---|---|
> prompts and nothing happens | the paste was cut off | Ctrl+C and paste the whole block |
| Windows: 'mkdir -p' or heredoc errors | PowerShell instead of a Linux shell | use WSL, or create the files by copying their content in VS Code |
Values, types, operators and input
Goal: Store data in variables, know its type, combine values with operators, and read input from the user.
Free account Create a free account or sign in to continue this course.
Strings: indexing, slicing, methods and formatting
Goal: Take text apart and build it back up: the core of log parsing and reporting.
Free account Create a free account or sign in to continue this course.
Control flow: decisions and loops
Goal: Make a program choose between paths, repeat work, and stop at the right moment.
Free account Create a free account or sign in to continue this course.
Collections: lists, tuples, dictionaries and sets
Goal: Choose the right container for ordering, looking up, counting and de-duplicating data.
Free account Create a free account or sign in to continue this course.
Functions and modules
Goal: Package logic into reusable, testable functions and organise code across files.
Free account Create a free account or sign in to continue this course.
Files, paths and regular expressions
Goal: Read and write files safely, handle paths portably, and extract fields reliably with regular expressions.
Free account Create a free account or sign in to continue this course.
Errors, command-line arguments and running programs
Goal: Handle failures deliberately, accept options on the command line, and run other programs safely.
Free account Create a free account or sign in to continue this course.
Data formats and web APIs
Goal: Save results as JSON and CSV, and enrich them from an HTTP API with timeouts and retries.
Free account Create a free account or sign in to continue this course.
Modelling data with classes
Goal: Replace loosely structured dictionaries with typed records that carry their own behaviour.
Free account Create a free account or sign in to continue this course.
Packages and automated testing
Goal: Install packages safely in a virtual environment and prove your code works with automated tests.
Free account Create a free account or sign in to continue this course.
Cheat sheet, assessment and expert challenge
Goal: Consolidate the syntax on one page, then build and test the finished tool on your own.
Free account Create a free account or sign in to continue this course.
Quick reference (the cheat-sheet lessons and the PDF content)
The Python toolbox
From idea to a tool others can run
Never install into the system Python. One virtual environment per project, dependencies pinned in a lock file.
Set up a project
uv init log-tool && cd log-tool
uv add httpx rich # runtime deps
uv add --dev pytest ruff mypy
uv run pytest # runs inside the venv
# no uv? the standard way:
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txtWhich Python version?
- 3.15 is current (October 2026): lazy imports, a built-in
frozendict, a faster experimental JIT - Use a supported release, 3.12 or newer, for new tools
- 3.10 reached end of life in October 2026: plan upgrades
- Pin the version in
pyproject.toml:requires-python = ">=3.12"
Script skeleton: the shape of every tool
import argparse, logging, sys
log = logging.getLogger(__name__)
def main(argv=None) -> int:
p = argparse.ArgumentParser(description="Count failed logins")
p.add_argument("logfile")
p.add_argument("-v", "--verbose", action="store_true")
a = p.parse_args(argv)
logging.basicConfig(level=logging.DEBUG if a.verbose else logging.INFO)
log.info("reading %s", a.logfile)
return 0
if __name__ == "__main__":
sys.exit(main())Syntax you will use every day
| Task | Idiom |
|---|---|
| Format a string | f"{user}@{host} failed {n:,} times" |
| Filter and transform | [ip for ip in ips if not ip.startswith("10.")] |
| Count things | Counter(ips).most_common(10) |
| Group things | by_user = defaultdict(list); by_user[u].append(evt) |
| Safe dict access | evt.get("src_ip", "unknown") |
| Loop with index | for i, line in enumerate(f, 1): |
| Unpack | ts, host, msg = line.split(" ", 2) |
| Match on structure | match evt: case {"type": "login", "ok": False}: ... |
| Typed record | @dataclass(frozen=True) class Alert: id: str; sev: int |
| Time in UTC | datetime.now(timezone.utc).isoformat() |
Pick the right data structure
| Need | Use | Why |
|---|---|---|
| Ordered items, may change | list | Append and sort; O(n) membership test |
| Fixed record | tuple or @dataclass(frozen=True) | Immutable, hashable, self-documenting |
| Lookup by key | dict | O(1) average lookup; keeps insertion order |
| Unique values, fast 'in' | set | Deduplicate IOCs; O(1) membership |
| Counting | collections.Counter | Top-N in one call |
| Queue or sliding window | collections.deque(maxlen=N) | Fast appends and pops at both ends |
| Read-only mapping | types.MappingProxyType; frozendict in 3.15 | Config that must not change at runtime |
Worked example: failed SSH logins by IP
import re, sys
from collections import Counter
from pathlib import Path
PAT = re.compile(r"Failed password for (?:invalid user )?(\S+) from (\S+)")
def top_offenders(path: Path, n: int = 10) -> list[tuple[str, int]]:
hits = Counter()
with path.open(encoding="utf-8", errors="replace") as f:
for line in f: # streams: works on huge files
if m := PAT.search(line):
user, ip = m.groups()
hits[ip] += 1
return hits.most_common(n)
if __name__ == "__main__":
for ip, count in top_offenders(Path(sys.argv[1])):
print(f"{count:>6} {ip}")Why it is written this way
- Compiles the regex once, outside the loop
- Reads line by line, so a 5 GB log never loads into memory
errors="replace"survives bad bytes in logs- Returns data; printing stays in
__main__, so it is testable - Type hints document the contract for the next person
Files and processes, safely
Never build a shell command from user input. Pass a list of arguments and leave shell=False.
from pathlib import Path
out = Path("reports") / "daily.csv"
out.parent.mkdir(parents=True, exist_ok=True)
for p in Path("/var/log").glob("auth.log*"):
print(p.name, p.stat().st_size)
text = Path("cfg.json").read_text(encoding="utf-8")import subprocess
# list form: no shell, no injection
r = subprocess.run(["systemctl", "is-active", svc],
capture_output=True, text=True,
timeout=10, check=False)
if r.returncode != 0:
log.warning("%s is %s", svc, r.stdout.strip())Calling APIs the production way
import os, time, httpx
TOKEN = os.environ["API_TOKEN"] # never hard-code secrets
def get_all(url: str) -> list[dict]:
items, headers = [], {"Authorization": f"Bearer {TOKEN}"}
with httpx.Client(timeout=15, headers=headers) as c:
while url:
for attempt in range(4):
r = c.get(url)
if r.status_code in (429, 502, 503):
time.sleep(2 ** attempt) # back off
continue
r.raise_for_status()
break
data = r.json()
items += data["items"]
url = data.get("next") # follow pages
return itemsChecklist for every API client
- Timeout on every call
- Retry only on 429 and 5xx, with backoff
- Respect
Retry-After - Follow pagination to the end
- Secrets from env or a vault
- Keep TLS verification on
Errors and logging: a decision guide
| Situation | Do this |
|---|---|
| You can fix it here (retry, default value) | Catch the specific exception and handle it |
| You cannot fix it | Let it raise; catch once at the top of main() and exit non-zero |
| You need context | raise ToolError(f"bad row {i}") from e |
| Something is odd but not fatal | log.warning(...) with the values that explain it |
Bare except: or except Exception: pass | Never: it hides bugs and Ctrl-C |
Test it with pytest
from ssh_fails import top_offenders
def test_counts_by_ip(tmp_path):
log = tmp_path / "auth.log"
log.write_text(
"Failed password for root from 203.0.113.5 port 22\n"
"Failed password for invalid user a from 203.0.113.5\n"
"Accepted password for bob from 198.51.100.7\n")
assert top_offenders(log) == [("203.0.113.5", 2)]Speed without guesswork
Measure, then fix
python -m cProfile -s cumtime tool.pyfinds the slow part- Use sets and dicts for lookups inside loops
- Stream files; avoid
.read()on big logs - I/O-bound work:
asyncioor a thread pool - CPU-bound work:
multiprocessing, or vectorize with pandas or polars
Secure coding: dangerous calls and safe swaps
| Avoid | Risk | Use instead |
|---|---|---|
subprocess(..., shell=True) with input | Command injection | Argument list, shell=False |
eval() / exec() on data | Code execution | json.loads, ast.literal_eval |
pickle.load from untrusted files | Code execution on load | JSON, or sign and verify the data |
yaml.load(f) | Object injection | yaml.safe_load(f) |
| SQL built with f-strings | SQL injection | Parameters: cur.execute(q, (user,)) |
verify=False on HTTPS | Man-in-the-middle | Fix the CA bundle |
random for tokens | Predictable secrets | secrets.token_urlsafe() |
| Unpinned dependencies | Supply-chain attack | Lock file, hashes, pip-audit |
ruff check --select S (the Bandit rules) on your project. It flags most of the patterns above before code review.Key terms
- Virtual environment
- An isolated set of packages for one project, created with venv or uv.
- pyproject.toml
- The standard file that declares a project's metadata, dependencies and tool settings.
- Lock file
- Exact versions (and hashes) of every dependency, so builds are reproducible.
- Type hints
- Annotations such as list[str] that document intent and let checkers like mypy catch bugs.
- pytest fixture
- Reusable setup for tests, such as tmp_path for a temporary directory.
- Command injection
- Running attacker-controlled text as a shell command, usually through shell=True.
Hands-on lab
Free account Create a free account or sign in to continue this course.
Knowledge check
Answer all five questions, then check your answers. Each answer comes with a short explanation.
Further reading
- Python documentation docs.python.org
- Python Packaging User Guide packaging.python.org
- pytest documentation docs.pytest.org
- Ruff linter rules docs.astral.sh
Put it into practice
Use these ThreatAI tools to apply what you learned to your own environment.