Unit 1: Python for defenders · Lesson 1 of 6 · 15 min
Running Python
Check the interpreter, run a script and test ideas one line at a time.
mission
- You are
- the new security engineer on the platform team
- Situation
- It is your first morning and the team keeps its small tools in
~/scripts. Before you change anything you check that Python works and that you can read and run what is there. - Goal
- Run an existing script, then answer a question about the inventory straight from the REPL.
- Hand in
- The number of hosts in the inventory and the Python version on the box.
From file to output
Check which Python you have
Scripts behave differently across versions, so a defender always checks the interpreter first.
python3 --version Python 3.12.3 which python3 /usr/bin/python3
you should see Python 3.12 living in /usr/bin.
defender tip On shared servers python may not exist or may be Python 2. Always type python3.
Read the script before you run it
Never run a script you have not read, even one from your own team.
cat scripts/hello.py
hosts = open("/home/learner/data/inventory.txt").read().splitlines()
print("Python is working.")
print(len(hosts), "hosts in data/inventory.txt")
you should see Three lines: read the inventory, print a greeting, print a count.
Run it
python3 scripts/hello.py
Python is working.
17 hosts in data/inventory.txt
you should see A host count taken from the inventory file.
Ask quick questions in the REPL
Type python3 alone to get the >>> prompt. It answers each line as you type it, which makes it the fastest way to test an idea before it goes into a script.
hosts = open('data/inventory.txt').read().splitlines() len(hosts) 17 hosts[0] 'web01 web ubuntu-24.04 22,80,443' hosts[-1] 'legacy01 file centos-7 21,22,23,111,445,2049,3306'
you should see The first and last lines of the inventory. Index -1 counts from the end.
defender tip Leave the REPL with exit() or Ctrl+D.
Run one line from the shell
python3 -c runs a short program without opening the REPL, handy inside shell pipelines.
python3 -c 'print(sum(1 for l in open("data/inventory.txt") if "windows" in l))'
6
you should see How many inventory lines mention windows.
What a defender takes away
- 1Check the interpreter version before you trust a script's behaviour.
- 2Read a script before you run it, every time.
- 3Use the REPL to test one idea at a time, then move it into a file.
Questions
0 of 3 solved
Answer each one from what you find on your lab machine.