Every level, in the open
Python for Ops
5 worlds · 52 levels · 6 bosses
SOLUTION HIDDENTeachers see answer keys in the classroom.
Real python3 on a real Linux box: the scripts an on-call engineer actually writes. Parse logs, CSV and JSON, replace fragile bash with subprocess, build argparse CLIs, talk to HTTP APIs, make idempotent changes and test your tools. Hidden tests run your scripts on inputs you never saw.
Guided levels show the command first. Alone levels give the goal only. Bosses and exams are timed.
Jump to a world
World 1The Snake Pit
13 levelsKern found a snake in the server room that counts instead of biting: your first python3 scripts: REPL, heredoc, types, lists, dicts, argv, files.
Level 1: First hiss
Objective: Open the python3 REPL, compute something, exit cleanly; then write ~/pit/hello.py that prints 'Snake Pit online' and run it.
python3 alone opens the REPL, where Python answers each expression and exit() or Ctrl-D brings you back to bash. To keep code, write hello.py with a quoted heredoc (cat > hello.py <<'EOF', the lines, then EOF) and run hidden.
Commands taught
py-replpy-heredoc-scriptpy-why-pythonLevel 2: Disk math
Objective: Write ~/pit/disk.py: read used GB, then total GB (one per line on stdin) and print 'Disk: <used*100//total>% used' and 'Free: <total-used> GB'.
input() reads one line of stdin, always as text (str), so '40' + '2' is '402'. int() turns text into a number so math works; // divides without the fraction. An f-string, f'Disk: {pct}% used', drops values straight into text.
Commands taught
py-int-strpy-fstringsLevel 3: Port sieve
Objective: Write ~/pit/ports.py: read one line of ports from stdin; print 'privileged: <port>' for each port below 1024 (in order), then 'count: <how many>'.
line.split() cuts text on spaces into a list: '22 80 8080'.split() is ['22', '80', '8080']. for p in ports: runs the indented block once per item; if int(p) < 1024: only for privileged ports. Python's blocks are its indentation (4 spaces), not do/done.
Commands taught
py-listspy-for-ifLevel 4: Status tally
Objective: Write ~/pit/tally.py: read one line of HTTP status codes from stdin and print '<code>: <count>' for each code, sorted by code.
A dict maps keys to values: counts = {}; counts['404'] = 1. counts.get(code, 0) gives the value or 0 if the key is new, so counts[code] = counts.get(code, 0) + 1 counts anything. sorted(counts) gives the keys in order. It is bash's declare -A, without the pain.
Commands taught
py-dictsLevel 5: First arguments
Objective: Make ~/pit/check.py executable: ./check.py svc1 svc2 … prints 'checking <svc>' for each argument.
Arguments land in sys.argv (import sys): [0] is the script, [1:] is everything typed after it. for svc in sys.argv[1:]: runs once per argument; print(f'checking {svc}') fills the value in. Line 1 #!/usr/bin/env python3 + chmod +x lets you run ./check.py.
Commands taught
py-argvpy-fstringspy-shebangLevel 6: Uptime tag
Objective: Write ~/pit/uptime.py: python3 uptime.py MINUTES prints 'up <h>h <m>m' (135 → 'up 2h 15m').
import sys gives you sys.argv, the command line as a list: sys.argv[0] is the script, sys.argv[1] the first argument, like $1 in bash. It is text, so int() it. m // 60 is whole hours, m % 60 the minutes left over.
Commands taught
py-argvLevel 7: Quota calc
Objective: Write ~/pit/quota.py with a function that returns the usage percent: python3 quota.py USED TOTAL LIMIT prints 'usage: <pct>%' then ALERT (pct >= LIMIT) or OK.
def pct(used, total): starts a function; its indented body ends with return, which hands a value back to the caller (bash functions can only return an exit code). Name a calculation once, reuse it everywhere.
Commands taught
py-functionsLevel 8: Read the lines
Objective: Write ~/pit/show.py: python3 show.py FILE prints every line of FILE stripped, skipping blank lines and lines that start with # (sample: ~/pit/hosts.txt).
with open(path) as f: opens a file and closes it for you. for line in f: gives one line at a time; line = line.strip() removes the newline and stray spaces. if not line catches a blank, line.startswith('#') a comment; continue skips it.
Commands taught
py-open-linesLevel 9: Host list
Objective: Write ~/pit/hosts.py: python3 hosts.py FILE prints every host in FILE (stripped, no blank or # lines), then 'total: <count>' (sample: ~/pit/hosts.txt).
with open(path) as f: opens a file and closes it for you when the block ends. for line in f: gives one line at a time, newline included; line.strip() removes it and stray spaces. Skip blanks with if not line and comments with line.startswith('#').
Commands taught
py-open-linesLevel 10: Own command
Objective: Make ~/pit/tool.py an executable python script: ./tool.py svc1 svc2 … prints 'checking <svc>' for each argument, then 'done: <count>'.
Same trick as bash: line 1 #!/usr/bin/env python3 tells the kernel which program runs the file (env finds python3 on PATH), chmod +x makes it runnable, and ./tool.py starts it with no python3 in front. sys.argv[1:] is every argument (bash's "$@").
Commands taught
py-shebangLevel 11: Slow pings
Objective: Make ~/pit/ping.py executable: ./ping.py FILE MAX prints 'SLOW <host> <ms>ms' for each host slower than MAX ms, then 'slow: <count>' (sample: ~/pit/probe.txt).
The second argument is sys.argv[2], but it is text: limit = int(sys.argv[2]). host, ms = line.split() unpacks 'web1 120' into two names. Compare numbers, not text: int(ms) > limit. A counter (slow = 0, slow += 1) keeps score.
Commands taught
py-open-linespy-fstringsLevel 12: PAGER: slow hosts
Objective: Make ~/pit/slow.py executable: ./slow.py FILE MAX prints 'SLOW <host> <ms>ms' per host above MAX ms, then 'slow: <n> of <hosts>'.
Pager at 03:12: the probe wrote one 'host latency_ms' line per machine, with blanks and # notes. On-call wants a real command: shebang, chmod +x, argv, open + strip, split, int() before you compare.
Level 13: BOSS: Fleet report
Objective: Write ~/pit/report.py: python3 report.py INVENTORY prints '<role>: <count>' per role sorted by role, then 'total: <hosts>'. ~/pit/inventory.txt is a sample.
The Pit's keeper wants a fleet report before the deploy: the inventory has one 'host role' line per machine, with blanks and # comments. Everything from this world in one script: argv, open + strip, split, a dict of counts, sorted, f-strings.
World 2The Ledger
10 levelsThe archive under the server room, where Kern swears every outage leaves a confession you can read with pathlib, CSV, JSON and regex.
Level 14: Shelf count
Objective: Write ~/ledger/shelf.py: for python3 shelf.py DIR print '<name> <bytes>' per *.log file in DIR (sorted), then 'total <bytes>'; no DIR: 'no such folder: DIR'.
pathlib turns paths into objects: Path('logs').glob('*.log') finds the logs, .is_file() skips folders, .stat().st_size is the size in bytes and .exists() asks before you touch. Before cleaning a disk, you measure it.
Commands taught
py-pathlibLevel 15: Error tally
Objective: Write ~/ledger/tally.py: python3 tally.py LOG prints '<service> <count>' for every service with ERROR lines, alphabetical.
line.split() cuts a log line on runs of spaces (a blank line gives []), so parts[1] is the level and parts[2] the service. Matching the word ERROR anywhere in the line counts the wrong lines.
Commands taught
py-splitLevel 16: Quoted commas
Objective: Write ~/ledger/bill.py: python3 bill.py CSV prints '<team> <total cost, 2 decimals>' per team, alphabetical; rows with an empty cost are skipped.
The billing export has a note column, and notes contain commas inside quotes: "VM, 2 vCPU". line.split(',') cuts them in pieces and the cost lands in the wrong column. csv.DictReader knows the CSV rules and hands you each row as a dict keyed by the header.
Commands taught
py-csvLevel 17: Config flip
Objective: Write ~/ledger/flip.py: python3 flip.py IN OUT sets log_level 'warn', version +1, writes OUT (indent 2, folders created), other keys kept.
Config files are JSON: json.load(f) gives you a dict, you change it like any dict, json.dump(obj, f, indent=2) writes it back readable. Deploy folders may not exist yet: Path(out).parent.mkdir(parents=True, exist_ok=True) makes them, and does nothing if they are there.
Commands taught
py-jsonLevel 18: Slow calls
Objective: Write ~/ledger/slow.py: python3 slow.py FILE MS prints '<path> <ms>' for each request slower than MS (in file order), then 'slow <count>'.
Many services log JSON lines: one complete JSON object per line, so the file is never loaded whole. json.loads(line) parses one line; event.get('ms') returns None when the key is missing instead of crashing.
Commands taught
py-jsonlLevel 19: Who knocked?
Objective: Write ~/ledger/users.py: python3 users.py AUTHLOG prints '<user> <failed logins>' for every user with failed password attempts, alphabetical.
auth.log lines differ: 'Failed password for root from …' and 'Failed password for invalid user admin from …'. One regular expression fits both: r'Failed password for (invalid user )?(\S+) from'. re.search finds it anywhere; group(2) is the user. r'' keeps backslashes.
Commands taught
py-reLevel 20: Top knockers
Objective: Write ~/ledger/top.py: python3 top.py AUTHLOG N prints the N IPs with the most failed passwords as '<ip> <count>', most first, ties in IP text order.
re.findall returns every captured IP, collections.Counter counts them. sorted(counts.items(), key=lambda item: (-item[1], item[0])) ranks by count, then IP text. most_common() breaks ties by first seen.
Commands taught
py-counterLevel 21: PAGER: Over budget
Objective: PAGER: write ~/ledger/over.py: python3 over.py CSV BUDGET OUT writes OUT as CSV team,item,note,cost : rows costing more than BUDGET, priciest first.
PAGER from finance: the cloud bill jumped and they want every line over budget in a spreadsheet before 9. csv.writer(f).writerow([...]) quotes fields with commas so notes stay in one cell; open the file with newline=''.
Commands taught
py-csv-writerLevel 22: PAGER: 5xx spike
Objective: PAGER: write ~/ledger/spike.py: python3 spike.py LOG prints '<HH:MM> <count>' for the minute with the most 5xx responses (tie: earliest), or 'no 5xx'.
PAGER 03:21: checkout is throwing 5xx and the incident channel needs to know which minute it started burning. The gateway's JSON-lines log is all you have.
Level 23: BOSS: The night digest
Objective: Build ~/ledger/digest.py step by step: python3 digest.py DIR OUT summarizes every app.log* file (incl. .gz) in DIR as JSON, prints it and saves it to OUT.
Logrotate keeps app.log, app.log.1, and older nights as app.log.2.gz, app.log.3.gz. The morning stand-up wants one JSON digest of the whole week: files, lines, and errors per service.
Commands taught
py-gzip
World 3The Engine Room
10 levelsOld bash scripts hiss and leak behind the boiler doors, so Kern hands you a Python wrench (subprocess, exit codes, argparse, logging) to fix the pipes.
Level 24: First call
Objective: Write ~/engine/count.py PATH: run wc -l on PATH and print only the number, or 'cannot count PATH' when wc's returncode is not 0.
subprocess.run(["wc", "-l", path], capture_output=True, text=True) starts a program straight away, no shell in between: every list item is one argument, so spaces and ; in a name stay part of the name. The result keeps .stdout (text) and .returncode (0 = it worked).
Commands taught
py-subprocessLevel 25: Fail loud
Objective: Write ~/engine/backup.py SRC DEST: copy with cp (check=True, timeout=5) and print 'backup ok', 'backup failed (exit N)' or 'backup timed out'.
check=True turns a failed command into an exception, subprocess.CalledProcessError (e.returncode says which exit). timeout=5 stops a command that hangs and raises subprocess.TimeoutExpired. Catch each one with try/except and say what happened.
Commands taught
py-check-timeoutLevel 26: Exit contract
Objective: ~/engine/logcheck.py FILE (grep -c ERROR): 'clean' exit 0 · 'N errors' exit 1 · unreadable: stderr, exit 1 · not 1 argument: usage on stderr, exit 2.
cron, CI and systemd never read your text: they read the exit code. sys.exit(0) = all good, sys.exit(1) = found a problem, sys.exit(2) = called wrong (usage). Messages for humans go to stderr with print(..., file=sys.stderr), so stdout stays clean data.
Commands taught
py-sys-exitLevel 27: Proper flags
Objective: ~/engine/rotate.py LOGDIR [--keep N=5] [--mode gzip|delete, default gzip] [--dry-run]: print dir=LOGDIR keep=N mode=MODE dry_run=True/False.
argparse turns sys.argv into a command line: add_argument("logdir") is a required positional, "--keep" with type=int converts and checks numbers, choices= limits values, action="store_true" makes an on/off flag. Bad input → usage on stderr + exit 2, and --help is written for you.
Commands taught
py-argparseLevel 28: Missing pieces
Objective: ~/engine/readcfg.py FILE: print port= as a number; on errors one stderr line with 'not found', 'permission' or 'not a number', exit 1, no traceback.
A traceback is a crash, not a message: catch the exception you expect, FileNotFoundError, PermissionError or ValueError (int("80a")), say it in one stderr line and exit 1. Never a bare except: it hides real bugs too.
Commands taught
py-try-exceptLevel 29: Quiet logs
Objective: ~/engine/sweep.py DIR [--verbose]: print only the count of *.tmp files, log INFO (level name shown) on stderr, and with --verbose a DEBUG line per .tmp file.
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") sets up logs once; logging.info / .debug / .warning / .error write them to stderr. Only messages at the level or above show, so --verbose switching to logging.DEBUG adds detail without touching stdout.
Commands taught
py-loggingLevel 30: Tool check
Objective: ~/engine/preflight.py TOOL…: print 'TOOL: PATH' for each found, name every missing one on stderr then exit 1 (else 0), and never run them.
shutil.which("tar") searches PATH like the shell does and returns the full path, or None if the tool is missing. Check every tool a script needs before doing any work: fail fast with a clear list, instead of dying halfway through.
Commands taught
py-shutil-whichLevel 31: Disk alarm
Objective: ~/engine/diskcheck.py [--threshold N=90]: df -P, print 'MOUNT USE%' per mount at/over N, exit 1; else 'disk ok', exit 0. df fails/hangs: stderr, exit 1.
Wrapping a tool means reading its output: df -P gives one line per filesystem, columns split by spaces, Capacity in column 5 ("87%") and the mount in column 6. Skip the header, split each line, strip the %, compare as int.
Commands taught
py-tool-outputLevel 32: Port watch
Objective: ~/engine/portcheck.py PORT...: ss -ltn, print 'PORT open'/'PORT closed' each; exit 0 if all open, else 1. ss missing/failing/hanging: stderr, exit 1.
ss -ltn lists listening TCP sockets; column 4 is Local Address:Port (0.0.0.0:22, [::]:22, *:8080), and the port is after the LAST colon: rsplit(":", 1)[1]. Compare whole numbers, never 'in' the line: 80 is in 8080.
Level 33: BOSS: The night shift
Objective: Port ~/engine/nightly.sh to ~/engine/nightly.py SRC DEST [--dry-run] [--verbose]: argparse, tar as a list, timeout, exit codes, stderr messages and logging.
nightly.sh archives a folder every night, but it never quotes its variables and ignores failures: a strange folder name runs commands, a failed tar still says 'archived' and exits 0. Port it to a Python CLI that cron can trust.
Commands taught
py-bash-to-python
World 4The Relay
8 levelsStatic on the radio tower that relays every service call. Kern climbs up with you to speak HTTP from Python and build a deploy gate that says no.
Level 34: First contact
Objective: Write ~/relay/services.py: GET http://api.relay/services (a JSON list) and print 'NAME VERSION' for each service, one per line.
urllib.request.urlopen(url, timeout=5) sends a GET and gives back a response. resp.read() is the body as bytes; json.loads() turns that JSON into Python lists and dicts. Use it in a with-block so the connection is closed.
Commands taught
py-urllib-getpy-relay-apiLevel 35: Dead air
Objective: ~/relay/svc.py NAME: GET /services/NAME (timeout=3). 200: 'NAME VERSION', exit 0. HTTP error: 'NAME: HTTP CODE', exit 1. No answer: 'NAME: unreachable', exit 2.
Two failures: the server ANSWERED with an error status (404, 500: urllib.error.HTTPError, e.code), or no answer came (no server: URLError; too slow: TimeoutError). HTTPError is a kind of URLError: catch it FIRST. timeout= caps the wait.
Commands taught
py-urllib-errorsLevel 36: Signed orders
Objective: ~/relay/deploy.py SERVICE VERSION: POST that JSON to http://api.relay/deploys, print 'deploy ID queued'. HTTP error: 'deploy rejected: HTTP CODE', exit 1.
To send data, build a urllib.request.Request: data= is the body as bytes (json.dumps(...).encode()), headers= says what it is (Content-Type: application/json), method="POST". The API answers 201 Created with JSON of its own.
Commands taught
py-urllib-postLevel 37: The long list
Objective: Write ~/relay/all.py: print every service name from every page of http://api.relay/services?page=N, one per line, and stop when next is null.
Big lists come in pages: /services?page=1 answers {"page": 1, "next": 2, "services": [...]}, the last page has "next": null (None in Python). Loop: fetch, print, follow next until it is None. A while loop runs as long as its condition is true.
Commands taught
py-http-pagesLevel 38: Try again
Objective: ~/relay/retry.py PATH: GET http://api.relay/PATH and print the body. 5xx: retry, 4 tries max, wait 0.3 s then double. 4xx: no retry. Failure: exit 1.
A 5xx means the server is struggling: wait and try again, a bit longer each time (backoff: 0.3 s, 0.6 s, 1.2 s, time.sleep). A 4xx means YOUR request is wrong: retrying sends the same wrong request, so stop at once. Always cap the tries.
Commands taught
py-http-retryLevel 39: The badge
Objective: ~/relay/rotations.py: GET /admin/rotations with Bearer $RELAY_TOKEN, print 'SERVICE KEY DUE' lines. No token: exit 2, no call. 401: exit 1.
Admin endpoints want a token: the header Authorization: Bearer TOKEN. The token is a secret, so it never goes in the code (code gets copied, committed, pasted): read it from the environment with os.environ.get("RELAY_TOKEN"). A wrong token gets 401.
Commands taught
py-http-authLevel 40: PAGER: Night watch
Objective: Pager: ~/relay/check.py NAME...: print 'NAME ok', 'NAME down (HTTP CODE)' or 'NAME unreachable' (timeout=2). Exit with the worst: 0 ok, 1 down, 2 unreachable.
Monitoring tools (Nagios, cron alerts, CI) read ONE thing: the exit code. 0 = all fine, 1 = something is down, 2 = we could not even ask. Check every service, never stop at the first problem, and let the worst status win.
Commands taught
py-health-exitLevel 41: BOSS: The deploy gate
Objective: ~/relay/gate.py SERVICE VERSION: deploy only when every service in /services is healthy. Retry blips, time out hangs, exit 0 / 1 closed / 2 API unreachable.
Friday, 17:55. Someone wants to ship. The gate is the script that says no: it asks the API for every service, checks each one's health, and POSTs the deploy only if all of them are healthy. It must not lie, not hang, and not panic at one blip.
Commands taught
py-deploy-gate
World 5The Workshop
11 levelsTemplates, test benches and a ticket printer that never sleeps. Kern's rule over the door: run it twice; if run two changes anything, it isn't done.
Level 42: Blank forms
Objective: Write ~/workshop/render.py TEMPLATE KEY=VALUE...: print the filled template; a missing key → 'missing key: NAME' on stderr, exit 1.
string.Template fills $name and ${name} holes in a text from a dict; $$ is a literal $. substitute() raises KeyError when a key is missing, safe_substitute() quietly leaves the hole: for configs you want the loud one.
Commands taught
py-templateLevel 43: Exactly once
Objective: Write ~/workshop/ensure_line.py FILE LINE: make LINE a line of FILE exactly once; print 'changed' if you wrote, 'ok' if it was already there.
Idempotent means: run it twice, the second run changes nothing. Look before you write: if the line is already there, say 'ok' and touch nothing; otherwise add it and say 'changed'. That is how Ansible reports every task.
Commands taught
py-idempotentLevel 44: Swap in place
Objective: Write ~/workshop/set_key.py FILE KEY VALUE: set KEY=VALUE, keep FILE.bak, swap in via temp file + os.replace, print changed; same value → 'ok', nothing touched.
Writing over a live config is a gamble: crash halfway and the service reads half a file. Write the new text to a temp file in the same folder, then os.replace(tmp, path): the swap is all or nothing. Keep the old one as .bak first.
Commands taught
py-atomic-writeLevel 45: Probes
Objective: Write ~/workshop/probe.py PORT MIN_FREE_MB: print 'port 7070 open' (or closed), then 'disk ok' (or low: MB free on /); exit 0 only if both are fine.
socket.create_connection((host, port), timeout=2) is the Python 'is anything listening?': it connects or raises OSError (refused, timed out). shutil.disk_usage(path).free is the free space in bytes, like df.
Commands taught
py-socket-probeLevel 46: Guard tests
Objective: Write ~/workshop/test_hostnames.py with unittest tests for every rule of normalize_host (hostnames.py), strong enough to catch each planted bug.
A test pins down what code must do. unittest is in every python3: a class extending unittest.TestCase, methods named test_…, self.assertEqual / assertTrue / assertRaises. Run them with python3 -m unittest. A good test fails when someone breaks the code.
Commands taught
py-unittestLevel 47: Report and dry run
Objective: report.py FILE [--report OUT] [--dry-run]: print 'lines: N' (non-blank); --report writes {"lines": N} to OUT, --dry-run: 'would write OUT' instead.
add_argument('--report') gives args.report (None when absent); add_argument('--dry-run', action='store_true') gives args.dry_run (dash becomes underscore), True only when typed. --report PATH saves a result; --dry-run touches nothing.
Commands taught
py-argparseLevel 48: One per host
Objective: Write ~/workshop/render_all.py INVENTORY TEMPLATE OUTDIR: OUTDIR/<name>.conf per host, print 'rendered N configs'; missing key → stderr, exit 1, no files.
One template, many hosts: the inventory (JSON) holds each host's values, the template the shape. Render every host first; write only when all of them worked, so a typo in host 40 never leaves you with 39 new configs and one old one.
Commands taught
py-inventory-renderLevel 49: Health board
Objective: Write ~/workshop/health.py CHECKS.json: for each check (type file/port/disk, unknown = FAIL) print 'OK name' or 'FAIL name' in order; exit 1 if any failed.
A health check tool reads its checks from a file, runs every one (a failure never stops the others), prints one line each and sums it up in the exit code. Monitors and cron read the exit code; humans read the lines.
Commands taught
py-health-checksLevel 50: PAGER: size limits
Objective: Write ~/workshop/test_sizes.py with unittest tests for every rule of parse_size (sizes.py), strong enough to catch five planted bugs.
Pager: a refactor of parse_size() shipped a bug and logs filled a disk, because nothing tested it. Mutation testing grades tests by breaking the code on purpose: a test suite that still passes against broken code is not guarding anything.
Commands taught
py-mutation-testingLevel 51: BOSS: TICKET OPS-311
Objective: Build ~/workshop/rotate.py LOGDIR [--days N] [--report FILE] (gzip old *.log into LOGDIR/archive, JSON report, idempotent, clean errors) and test_rotate.py.
TICKET OPS-311: /var/log on the build box filled up again. Wanted: a tool cron can run every night that archives old logs, writes a report the dashboard reads, changes nothing on a second run, and comes with tests.
Commands taught
py-rotateLevel 52: BOSS: TICKET OPS-412
Objective: Build ~/workshop/rollout.py INVENTORY TEMPLATE DEST [--dry-run]: render per host, write only changes, atomic + .bak, a diff on --dry-run, exit codes.
TICKET OPS-412: roll the new app.conf out to every host in the inventory. Change only what differs, never leave a half-written file, and give the reviewer a --dry-run diff before anything is touched.
Commands taught
py-difflib
For teachers
Use these levels with a class
SOLUTION HIDDEN Teachers see answer keys in the classroom.