Sign in Start free

EngineeringFree course

Python for Automation and Security

Write small, safe, testable Python: project setup, everyday idioms, files and processes, API clients with retries, tests and secure coding.

  • Level Junior → Mid
  • Time 235 min
  • Modules 12
  • Exercises 24 with worked solutions
  • Includes Lab, 5-question quiz, references

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

  1. 0Start here: Python, installation and the course projectJuniorMidExpert20 min · 0 exercises
  2. 1Values, types, operators and inputJuniorMidExpert20 min · 3 exercises
  3. 2Strings: indexing, slicing, methods and formattingJuniorMidExpert15 min · 2 exercises
  4. 3Control flow: decisions and loopsJuniorMidExpert25 min · 4 exercises
  5. 4Collections: lists, tuples, dictionaries and setsJuniorMidExpert25 min · 4 exercises
  6. 5Functions and modulesJuniorMidExpert20 min · 1 exercises
  7. 6Files, paths and regular expressionsJuniorMidExpert25 min · 2 exercises
  8. 7Errors, command-line arguments and running programsJuniorMidExpert20 min · 2 exercises
  9. 8Data formats and web APIsJuniorMidExpert20 min · 2 exercises
  10. 9Modelling data with classesJuniorMidExpert15 min · 1 exercises
  11. 10Packages and automated testingJuniorMidExpert20 min · 1 exercises
  12. 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.

0

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.

20 min

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.

scan.pyyour source codepython3compiles to bytecode, runs itStandard libraryjson, re, pathlib, csv …Operating systemfiles, network, processesThird-party packagespytest, httpx (module 10)No separate build step: edit the file, run it again, see the result.
Pythonwhat you will learnValues and typesint, float, str, bool, Noneoperators, conversionControl flowif / elif / else, matchfor, while, breakCollectionslist, tuple, dict, setcomprehensionsFunctions and modulesdef, parameters, returnimport, standard libraryFiles, errors, CLIwith open, pathlib, retry / except, argparseProfessional toolsJSON, CSV, HTTP APIsdataclasses, venv, pytest

Quick check: What happens when you run python3 scan.py?

SymptomLikely causeFix
'python3: command not found'Python not installed or not on the PATHfollow 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.

Then install VS Code from code.visualstudio.com and its Python extension.

python3Run Python: a file, a one-liner, or the interactive prompt.Read-only
Syntaxpython3 [file.py | -c 'code' | -m module]
Parameters
file.pyrun a program file
-c 'code'run one line
(nothing)open the interactive prompt (REPL); leave with exit()
--versionprint the version
Example
shell
python3 --version
python3 -c 'print(2 ** 10)'
Output
Expected output
Python 3.13.18
1024
Verify

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.

In the interactive prompt
>>> 7 * 6
42
SymptomLikely causeFix
Windows opens the Microsoft Store when typing pythonan app alias is activeinstall Python, or use py
version 3.8 or olderan old system Python is first on the PATHinstall 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.

1
Comment. Starts with #. Ignored by Python; written for people.
2
Variable. A name bound to a value with =. Later lines use the name to refer to the value.
4
Condition. An expression that is True or False. in tests whether one string contains another.
python · scan.py
# scan.py: flag one log line
line = "Failed password for root"
if "Failed" in line:
    print("ALERT:", line)
3
String value. Text, written between quotes.
6
Function call. print runs with two arguments, separated by a comma, and writes them to the screen.
5
Indentation. Four spaces mark the lines that belong to the if. The colon at the end of the if line opens the block.
Output
ALERT: Failed password for root

Quick check: Which part decides whether line 4 runs?

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.

Steps 1-3text, loops, countsStep 4functions, moduleStep 5parse with regexStep 6CLI and errorsStep 7JSON, CSV, APISteps 8-9classes, tests
shell · project step 0 (paste once)
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")
PY
Expected output
lab 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.

SymptomLikely causeFix
> prompts and nothing happensthe paste was cut offCtrl+C and paste the whole block
Windows: 'mkdir -p' or heredoc errorsPowerShell instead of a Linux shelluse WSL, or create the files by copying their content in VS Code
1

Values, types, operators and input

Goal: Store data in variables, know its type, combine values with operators, and read input from the user.

20 min

Free account Create a free account or sign in to continue this course.

2

Strings: indexing, slicing, methods and formatting

Goal: Take text apart and build it back up: the core of log parsing and reporting.

15 min

Free account Create a free account or sign in to continue this course.

3

Control flow: decisions and loops

Goal: Make a program choose between paths, repeat work, and stop at the right moment.

25 min

Free account Create a free account or sign in to continue this course.

4

Collections: lists, tuples, dictionaries and sets

Goal: Choose the right container for ordering, looking up, counting and de-duplicating data.

25 min

Free account Create a free account or sign in to continue this course.

5

Functions and modules

Goal: Package logic into reusable, testable functions and organise code across files.

20 min

Free account Create a free account or sign in to continue this course.

6

Files, paths and regular expressions

Goal: Read and write files safely, handle paths portably, and extract fields reliably with regular expressions.

25 min

Free account Create a free account or sign in to continue this course.

7

Errors, command-line arguments and running programs

Goal: Handle failures deliberately, accept options on the command line, and run other programs safely.

20 min

Free account Create a free account or sign in to continue this course.

8

Data formats and web APIs

Goal: Save results as JSON and CSV, and enrich them from an HTTP API with timeouts and retries.

20 min

Free account Create a free account or sign in to continue this course.

9

Modelling data with classes

Goal: Replace loosely structured dictionaries with typed records that carry their own behaviour.

15 min

Free account Create a free account or sign in to continue this course.

10

Packages and automated testing

Goal: Install packages safely in a virtual environment and prove your code works with automated tests.

20 min

Free account Create a free account or sign in to continue this course.

11

Cheat sheet, assessment and expert challenge

Goal: Consolidate the syntax on one page, then build and test the finished tool on your own.

10 min

Free account Create a free account or sign in to continue this course.

Quick reference (the cheat-sheet lessons and the PDF content)
1

The Python toolbox

Junior
PythonautomationCore languagetypes, functions, classes,comprehensions, f-stringsDatalist, dict, set, dataclass,json, csv, re, collectionsFiles and OSpathlib, subprocess,shutil, tempfile, os.environHTTP and APIshttpx or requests, retries,timeouts, paginationQualitypytest, ruff, mypy,logging, typingPackagingvenv or uv, pyproject.toml,lock files, pinned versions
2

From idea to a tool others can run

JuniorMid

Never install into the system Python. One virtual environment per project, dependencies pinned in a lock file.

Isolateuv venv / python -m venvDeclarepyproject.tomlLintruff check, ruff formatType-checkmypy or pyrightTestpytestShiplock, tag, release

Set up a project

shell
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.txt

Which 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

python
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())
3

Syntax you will use every day

Junior
TaskIdiom
Format a stringf"{user}@{host} failed {n:,} times"
Filter and transform[ip for ip in ips if not ip.startswith("10.")]
Count thingsCounter(ips).most_common(10)
Group thingsby_user = defaultdict(list); by_user[u].append(evt)
Safe dict accessevt.get("src_ip", "unknown")
Loop with indexfor i, line in enumerate(f, 1):
Unpackts, host, msg = line.split(" ", 2)
Match on structurematch evt: case {"type": "login", "ok": False}: ...
Typed record@dataclass(frozen=True) class Alert: id: str; sev: int
Time in UTCdatetime.now(timezone.utc).isoformat()
4

Pick the right data structure

JuniorMid
NeedUseWhy
Ordered items, may changelistAppend and sort; O(n) membership test
Fixed recordtuple or @dataclass(frozen=True)Immutable, hashable, self-documenting
Lookup by keydictO(1) average lookup; keeps insertion order
Unique values, fast 'in'setDeduplicate IOCs; O(1) membership
Countingcollections.CounterTop-N in one call
Queue or sliding windowcollections.deque(maxlen=N)Fast appends and pops at both ends
Read-only mappingtypes.MappingProxyType; frozendict in 3.15Config that must not change at runtime
5

Worked example: failed SSH logins by IP

JuniorMid
python · ssh_fails.py
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
6

Files and processes, safely

JuniorMid

Never build a shell command from user input. Pass a list of arguments and leave shell=False.

python · pathlib
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")
python · subprocess
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())
7

Calling APIs the production way

Mid
python · httpx with retries and pagination
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 items

Checklist 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
8

Errors and logging: a decision guide

JuniorMid
SituationDo this
You can fix it here (retry, default value)Catch the specific exception and handle it
You cannot fix itLet it raise; catch once at the top of main() and exit non-zero
You need contextraise ToolError(f"bad row {i}") from e
Something is odd but not fatallog.warning(...) with the values that explain it
Bare except: or except Exception: passNever: it hides bugs and Ctrl-C
9

Test it with pytest

JuniorMid
python · test_ssh_fails.py
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)]
10

Speed without guesswork

MidExpert

Measure, then fix

  • python -m cProfile -s cumtime tool.py finds the slow part
  • Use sets and dicts for lookups inside loops
  • Stream files; avoid .read() on big logs
  • I/O-bound work: asyncio or a thread pool
  • CPU-bound work: multiprocessing, or vectorize with pandas or polars
11

Secure coding: dangerous calls and safe swaps

MidExpert
AvoidRiskUse instead
subprocess(..., shell=True) with inputCommand injectionArgument list, shell=False
eval() / exec() on dataCode executionjson.loads, ast.literal_eval
pickle.load from untrusted filesCode execution on loadJSON, or sign and verify the data
yaml.load(f)Object injectionyaml.safe_load(f)
SQL built with f-stringsSQL injectionParameters: cur.execute(q, (user,))
verify=False on HTTPSMan-in-the-middleFix the CA bundle
random for tokensPredictable secretssecrets.token_urlsafe()
Unpinned dependenciesSupply-chain attackLock file, hashes, pip-audit
Try it Run 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.

1Why read a log file line by line instead of with .read()?
2Which call is safe with a user-supplied hostname?
3Best structure for fast 'is this IOC known?' checks:
4An API returns 429. What should the client do?
5Safe replacement for yaml.load on untrusted files:

Further reading

Put it into practice

Use these ThreatAI tools to apply what you learned to your own environment.