Python for Cybersecurity Beginners: Automation Basics and 6 Mini Projects
Learn the Python you actually need for security tasks: variables, loops, functions, files and regex. Then build six small tools with full code and the output you should see.
Independent study aid. Not affiliated with or endorsed by Google or Coursera. All explanations and code are original. Check the official Python documentation for details. Only run these scripts on data and systems you own or are allowed to use.
1. Why Python in security?
Analysts repeat the same jobs: reading logs, counting events, checking lists, validating files. Python turns those into short scripts that run in seconds and give the same result every time.
Setup
Install Python 3 from python.org. Save code as name.py and run python3 name.py.
Mindset
Start small, print results often, and test with sample data before touching real logs.
Builds on
Pairs well with Linux and SQL skills from earlier courses. See the Course 7 notes.
2. Python basics for security work
Variables and data types
A variable is a named box holding a value. Common types: string (str), integer (int), boolean (bool), list, dictionary.
ip = "203.0.113.9"
attempts = 5
is_blocked = False
watchlist = ["10.0.0.5", "10.0.0.8"]
user_fails = {"bob": 3, "alice": 1}
print(ip, attempts, is_blocked)
Expected output
203.0.113.9 5 False
Loops and conditions
for repeats over items; if makes decisions. Indentation (4 spaces) defines what belongs inside.
for port in [22, 80, 443]:
if port == 22:
print(port, "SSH - check access rules")
else:
print(port, "web port")
Expected output
22 SSH - check access rules 80 web port 443 web port
A while loop repeats until a condition changes, for example reading until a file ends.
Functions
A function packages steps so you can reuse them. return sends a result back.
def is_private(ip):
return ip.startswith("10.") or ip.startswith("192.168.")
print(is_private("10.0.0.5"))
print(is_private("8.8.8.8"))
Expected output
True False
Working with files
Use with open(...) so the file closes automatically. Modes: "r" read, "w" write (overwrites), "a" append.
with open("auth.log", "w") as f:
f.write("login ok\nlogin failed\nlogin failed\n")
with open("auth.log", "r") as f:
lines = f.read().splitlines()
print(len(lines), lines[1])
Expected output
3 login failed
Regular expressions (regex)
Regex describes text patterns. Use Python’s built-in re module. Handy pieces: \d digit, \w word character, + one or more, ( ) capture group.
import re
line = "user=bob action=login status=failed"
print(re.findall(r"user=(\w+)", line))
print(bool(re.search(r"status=failed", line)))
Expected output
['bob'] True
3. Six mini projects
Each script uses built-in sample data so you can run it straight away. Later, swap the sample for a real file you are permitted to read.
Project 1: Log parser
Goal: count log levels and failed events.
logs = [
"2026-10-01 09:12:03 INFO user=alice action=login status=success",
"2026-10-01 09:15:41 WARNING user=bob action=login status=failed",
"2026-10-01 09:16:02 ERROR user=bob action=login status=failed",
"2026-10-01 09:20:10 INFO user=carol action=upload status=success",
]
counts = {}
failed = 0
for line in logs:
level = line.split()[2]
counts[level] = counts.get(level, 0) + 1
if "status=failed" in line:
failed += 1
for level, n in counts.items():
print(level, n)
print("Failed events:", failed)
Expected output
INFO 2 WARNING 1 ERROR 1 Failed events: 2
Project 2: Allow-list checker
Goal: flag connections from addresses not on an approved list. A set makes lookups fast.
allowed = {"10.0.0.5", "10.0.0.8", "192.168.1.20"}
requests = ["10.0.0.5", "203.0.113.9", "192.168.1.20", "198.51.100.4"]
for ip in requests:
if ip in allowed:
print(ip, "ALLOWED")
else:
print(ip, "BLOCKED")
Expected output
10.0.0.5 ALLOWED 203.0.113.9 BLOCKED 192.168.1.20 ALLOWED 198.51.100.4 BLOCKED
Project 3: Password strength checker
Goal: score a password on length, mixed case, digits and symbols. This is a teaching toy; real policies should follow current official guidance. Never log or store real passwords.
import re
def check(pw):
score = 0
if len(pw) >= 12:
score += 1
if re.search(r"[a-z]", pw) and re.search(r"[A-Z]", pw):
score += 1
if re.search(r"\d", pw):
score += 1
if re.search(r"[^A-Za-z0-9]", pw):
score += 1
return ["Weak", "Weak", "Fair", "Good", "Strong"][score]
for pw in ["password", "Summer2026", "Tr0ub4dor&3x!"]:
print(pw, "->", check(pw))
Expected output
password -> Weak Summer2026 -> Fair Tr0ub4dor&3x! -> Strong
Project 4: Failed-login counter
Goal: count failures per user and raise an alert at 3 or more, a simple brute-force signal.
events = [("bob", "failed"), ("alice", "success"), ("bob", "failed"),
("bob", "failed"), ("dave", "failed"), ("dave", "failed")]
fails = {}
for user, status in events:
if status == "failed":
fails[user] = fails.get(user, 0) + 1
for user, n in fails.items():
flag = "ALERT" if n >= 3 else "ok"
print(user, n, flag)
Expected output
bob 3 ALERT dave 2 ok
Project 5: IP address extractor
Goal: pull every IPv4-looking address out of free text, then list the unique ones. The pattern matches the shape only; it does not check each number is 0-255.
import re
text = "Blocked 203.0.113.9 and 198.51.100.4. Retry from 203.0.113.9 failed; host 10.0.0.5 ok."
ips = re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", text)
print(ips)
print(sorted(set(ips)))
Expected output
['203.0.113.9', '198.51.100.4', '203.0.113.9', '10.0.0.5'] ['10.0.0.5', '198.51.100.4', '203.0.113.9']
Project 6: File hash checker
Goal: compute a SHA-256 hash with the built-in hashlib module and compare it to a trusted value to detect changes.
import hashlib
with open("sample.txt", "w") as f:
f.write("hello")
def sha256_of(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
h.update(chunk)
return h.hexdigest()
expected = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
actual = sha256_of("sample.txt")
print(actual)
print("MATCH" if actual == expected else "MISMATCH")
Expected output
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 MATCH
Change the file text to “Hello” and the result becomes MISMATCH, showing how a tiny change alters the hash.
4. Key terms
| Term | Plain meaning |
|---|---|
| Script | A file of Python instructions run top to bottom |
| List / dictionary / set | Ordered items / key-value pairs / unique items |
| Function | Reusable named block of code |
| Regex | A pattern used to find text |
| Parsing | Breaking text into useful parts |
| Allow-list | Approved items; everything else is denied |
| Hash | Fixed-length fingerprint of data |
| Brute force | Many repeated guesses at credentials |
| IOC | Indicator of compromise, such as a bad IP or hash |
5. Common mistakes
- Wrong indentation. Python uses it to group code; mix of tabs and spaces causes errors.
- Opening a file in
"w"mode by accident, which erases it. Use"r"or"a"when unsure. - Trusting regex blindly. Test patterns on good and bad samples.
- Skipping edge cases: empty lines, missing fields, unexpected formats.
- Using real data or secrets in tests. Use invented samples.
6. Practice questions (tap to reveal)
Q1. Why use a set for an allow-list?
Sets hold unique items and check membership quickly, which suits large lists of approved addresses.
Q2. What does with open(...) do for you?
It closes the file automatically, even if an error occurs.
Q3. What is the difference between re.search and re.findall?
search finds the first match; findall returns every match as a list.
Q4. How could Project 4 be improved for real logs?
Read from a file, group failures by time window, and include source IP as well as username.
Q5. Why does changing one character change a SHA-256 hash completely?
Hash functions are designed so small input changes produce very different outputs, which makes tampering easy to spot.
7. YouTube search links
- Python for cybersecurity beginners
- Python regex tutorial
- Python log parsing
- Python file hashing with hashlib
8. One-screen revision summary
- Variables store data; loops repeat; functions reuse logic.
- Files:
with open(); read"r", write"w", append"a". - Regex:
re.findall,re.search,\d,\w, groups. - Projects: log parser, allow-list, password checker, failed-login counter, IP extractor, hash checker.
- Safe practice: invented data, permission first, test edge cases.
Related pages
Educational summary for learners; not affiliated with Google or Coursera. Verify details against official materials. Last reviewed: October 2026.
