Python › Module 1 › Lesson 4
Lab — First Python Script
Write and run a small security-flavored script that reads a file and prints matching lines
Opening
Mini hunter: find failed logins
Create a tiny script that reads a sample log and prints lines containing "Failed password". This is the DNA of every log analyzer you will meet later.
1. Step 1 — Create a sample log
sample_auth.log (save next to your script)sshd: Failed password for root from 10.0.0.5 port 51234 sshd: Accepted password for alice from 10.0.0.9 port 51111 sshd: Failed password for admin from 10.0.0.5 port 51235 sshd: Failed password for root from 203.0.113.10 port 44022
sshd: Failed password for root from 10.0.0.5 port 51234 sshd: Accepted password for alice from 10.0.0.9 port 51111 sshd: Failed password for admin from 10.0.0.5 port 51235 sshd: Failed password for root from 203.0.113.10 port 44022
2. Step 2 — Write the script
find_failed.py — copy and runneedle = "Failed password" path = "sample_auth.log" with open(path, "r", encoding="utf-8") as f: for line in f: if needle in line: print(line.strip())
needle = "Failed password"
path = "sample_auth.log"
with open(path, "r", encoding="utf-8") as f:
for line in f:
if needle in line:
print(line.strip())3. Step 3 — Run it
Run from the same folderpython find_failed.py python3 find_failed.py
python find_failed.py python3 find_failed.py
You should see three failed-password lines. Challenge: also count how many failures came from 10.0.0.5.
Complete first Python script lab
Create sample_auth.log and find_failed.py, run the script, and confirm failed-password lines printed. Optional: count failures per IP.
Knowledge Check
What does if needle in line: check?
Multiple choice
Knowledge Check
True or False: This lab teaches a pattern used in real log hunting.
True or False