← All lessons Stage 1 · Lesson 7
25 min

Python for security: your first useful tools

Stage 1 · Lesson 7 · 25 minutes · Requires Lesson 6


The one-line answer

Python is the language security teams reach for when a task outgrows a Bash one-liner — it reads like plain English, and a thirty-line script can parse logs, check files and talk to websites for you.


Why you should care

Bash is perfect for gluing commands together. It gets painful the moment you need to count things properly, handle messy data, or talk to the web.

That is where Python takes over, and it is everywhere in this field: SOC teams use it to triage alerts, incident responders use it to sift evidence, penetration testers use it to automate checks, and almost every security tool you will meet either is written in Python or can be driven by it.

You do not need to become a software developer. You need the basics below, and three small tools you will build in this lesson and keep using.


How it actually works

Getting set up

In WSL, Mac or Linux, Python 3 is usually installed already:

python3 --version

On Windows without WSL, install it from python.org and tick "Add Python to PATH" during setup. On Windows the command is often py instead of python3.

For each project, create a virtual environment — a private folder of packages, so projects do not interfere with each other:

mkdir pytools && cd pytools
python3 -m venv .venv
source .venv/bin/activate        # Windows PowerShell: .venv\Scripts\Activate.ps1
pip install requests

Your prompt now starts with (.venv). Type deactivate to leave it.

The building blocks

Type python3 to get an interactive prompt (>>>) and try each of these. exit() leaves it.

Values and variables

name = "priya"            # text (a string)
attempts = 3              # whole number (an int)
blocked = True            # True or False (a bool)
print(f"{name} failed {attempts} times")

That f"..." is an f-string: anything inside { } is replaced with its value. You will use it constantly.

Lists — an ordered collection

ips = ["10.2.14.9", "203.0.113.44", "198.51.100.7"]
print(ips[0])             # first item: 10.2.14.9
ips.append("192.0.2.1")   # add one
print(len(ips))           # how many: 4

Dictionaries — look things up by name

user = {"name": "priya", "role": "viewer", "uid": 1042}
print(user["role"])       # viewer
user["role"] = "admin"    # change a value

If that looks familiar, it should: it is the same shape as the JSON in the session cookie from Challenge 08.

Decisions and loops

for ip in ips:
    if ip.startswith("10."):
        print(ip, "is private")
    else:
        print(ip, "is public")

Indentation is the syntax. Python uses the spaces at the start of a line to know what belongs inside the for and the if. Use four spaces, consistently.

Functions

def is_private(ip):
    return ip.startswith(("10.", "192.168.", "127."))

print(is_private("10.2.14.9"))    # True

(Stage 0 Lesson 1 covered the private ranges. This simple check skips 172.16–31 to stay short — the ipaddress module handles every range properly: ipaddress.ip_address(ip).is_private.)

Modules — code someone already wrote

import base64, hashlib

print(base64.b64decode("YWRtaW46cGFzc3dvcmQxMjM=").decode())   # admin:password123
print(hashlib.sha256(b"hello").hexdigest())

Python ships with modules for almost everything. The ones you will use most in security:

ModuleUsed for
sysReading command-line arguments
collectionsCounter — counting things in one line
reSearching text with patterns
hashlibMD5, SHA-256 and other hashes (Stage 0 Lesson 6)
base64Encoding and decoding
jsonReading and writing JSON
ipaddressWorking with IP addresses correctly
requestsTalking to websites (installed with pip)

Tool 1 — log analyser (the Python version of Lesson 6)

Save this as failed_logins.py:

#!/usr/bin/env python3
"""Top source IPs for failed SSH logins."""
import sys
from collections import Counter


def main():
    if len(sys.argv) < 2:
        print(f"usage: {sys.argv[0]} <auth.log> [how-many]", file=sys.stderr)
        sys.exit(1)

    path = sys.argv[1]
    top = int(sys.argv[2]) if len(sys.argv) > 2 else 10

    counts = Counter()
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            if "Failed password" in line:
                parts = line.split()
                ip = parts[-4]        # "... from <IP> port <N> ssh2"
                counts[ip] += 1

    print(f"Failed SSH logins in {path}: {sum(counts.values())}")
    print(f"Top {top} source addresses:")
    for ip, n in counts.most_common(top):
        print(f"{n:>6}  {ip}")


if __name__ == "__main__":
    main()

What is new:

  • with open(...) as f: opens the file and closes it automatically afterwards, even if something goes wrong.
  • errors="replace" — real logs contain odd bytes. This stops one bad character crashing the whole run.
  • line.split() breaks a line into words. parts[-4] counts from the end: ssh2 is -1, the port number -2, the word port -3, and the IP -4.
  • Counter counts for you; most_common(10) returns the top ten, already sorted.
  • if __name__ == "__main__": means "run main() only when this file is run directly" — so other scripts can import your function without triggering it.

It gives the same answer as the Bash script, but it is far easier to extend — group by username, flag private addresses, export to CSV — each is a few more lines.

Tool 2 — file integrity checker

Stage 0 Lesson 6 explained that a hash is a fingerprint: change one byte and it changes completely. Defenders use exactly this to prove a file has not been tampered with.

Save as hashcheck.py:

#!/usr/bin/env python3
"""Print the SHA-256 of a file, or compare it with an expected value."""
import hashlib
import sys


def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:                 # "rb" = read raw bytes
        while chunk := f.read(65536):           # 64 KB at a time
            h.update(chunk)
    return h.hexdigest()


if len(sys.argv) < 2:
    sys.exit(f"usage: {sys.argv[0]} <file> [expected-sha256]")

actual = sha256_of(sys.argv[1])
print(actual)

if len(sys.argv) > 2:
    if actual == sys.argv[2].lower():
        print("MATCH: file is unchanged")
    else:
        print("MISMATCH: file differs from the expected value")
        sys.exit(2)
  • "rb" opens the file as raw bytes. Hashes work on bytes; text mode can silently change line endings and give a different hash.
  • Reading in chunks keeps memory use tiny, even for a multi-gigabyte disk image.
  • while chunk := f.read(65536): reads a piece, and stops when nothing is left. (The := needs Python 3.8 or newer.)

This is how you verify a downloaded tool against the checksum its publisher lists, and how incident responders prove evidence was not altered.

Tool 3 — security header checker

Stage 1 Lesson 4 listed the security headers a defender configures. This checks which ones a site sends. Save it as headers_check.py:

#!/usr/bin/env python3
"""Report which recommended security headers a site sends."""
import sys
import requests

WANTED = [
    "Strict-Transport-Security",
    "Content-Security-Policy",
    "X-Content-Type-Options",
    "X-Frame-Options",
    "Referrer-Policy",
]

if len(sys.argv) < 2:
    sys.exit(f"usage: {sys.argv[0]} <https://your-site>")

url = sys.argv[1]
r = requests.get(url, timeout=10)
print(f"{url} -> {r.status_code}")
for name in WANTED:
    status = "present" if name in r.headers else "MISSING"
    print(f"  {name:<28} {status}")
  • requests.get(url, timeout=10) fetches the page — one ordinary request, exactly like opening it in a browser. Always set a timeout, or a slow server can hang your script forever.
  • r.headers is a dictionary of response headers, and it ignores upper/lower case for you.

See it yourself

Work inside your pytools folder with the virtual environment active.

1. Run the log analyser on the sample-auth.log you created in Lesson 6:

python3 failed_logins.py sample-auth.log 5

You should get the same result as the Bash script: 3 failures, 203.0.113.44 on top with 2.

2. Prove the avalanche effect.

echo "quarterly report" > report.txt
python3 hashcheck.py report.txt
echo "quarterly report." > report.txt
python3 hashcheck.py report.txt

One full stop changed the entire hash. Now confirm your tool against the system's own: sha256sum report.txt must print the same value.

3. Check security headers. Run it against a large, well-run site, and then against your own if you have one:

python3 headers_check.py https://github.com

Compare the result with what curl -I showed you in Lesson 4.

4. Push it to your portfolio. Commit all three tools to your security-writeups repository with a README for each. Three small, working, documented tools are real evidence of skill.

Boundary: the header checker makes one normal request — the same as visiting the homepage. Keep it that way. Turning a script into something that sends many requests, guesses logins, or probes a system you do not own is automated unauthorised access. Stage 0 Lesson 9 applies, and automation makes it more serious, not less.


How attackers abuse this

Python is a defender's tool and an attacker's tool. These are the patterns to recognise and avoid.

Fake packages with near-identical names. Malicious packages are regularly uploaded to PyPI under names one letter away from popular ones — reqeusts instead of requests. One typo in pip install runs a stranger's code on your machine. Copy package names from the official project page, and install only what you need.

Secrets committed to GitHub. API_KEY = "sk_live_..." inside a script, pushed to a public repository. Automated bots scan GitHub for keys continuously and find them within minutes. Deleting the line in a later commit does not help — it stays in the history. Keep secrets in environment variables or a .env file listed in .gitignore, and if one leaks, revoke it immediately.

Running untrusted input as code. eval() executes text as Python, and pickle.load() can run code hidden inside a file. Never use either on data from a user, a website or a download. Use json for data instead.

Switching off certificate checks. requests.get(url, verify=False) makes an error go away by disabling HTTPS certificate verification — which removes the protection against interception that Stage 1 Lesson 3 described. Fix the certificate problem instead.

A blue-team tip. The requests library announces itself as User-Agent: python-requests/2.x unless changed. In web server logs, sudden bursts from that user agent are often automated scanning — exactly the kind of signal a SOC analyst learns to spot.


Common mistakes

Inconsistent indentation. Mixing tabs and spaces, or three spaces and four, gives IndentationError. Set your editor to insert four spaces.

= versus ==. = assigns a value; == compares two values. if role = "admin": is an error.

Naming your file after a module. Save your script as requests.py and import requests imports your file instead of the library, failing with has no attribute 'get'. Name scripts after what they do.

Bytes versus text. base64.b64decode(...) returns bytes (b'admin:...'). Call .decode() to turn bytes into text.

Installing everything globally. Without a virtual environment, projects fight over package versions. One .venv per project.

No timeout on web requests. Without timeout=, a script can hang forever on an unresponsive server.


Check yourself

  1. Your script is saved as requests.py and fails with AttributeError: module 'requests' has no attribute 'get'. Why?
  2. Why does hashcheck.py open the file in "rb" mode?
  3. A teammate pushes API_KEY = "sk_live_..." to a public repository, notices, and deletes the line in the next commit. Is the key now safe?
Answers
  1. Python looks in the current folder first, so import requests loads your own requests.py instead of the library — and your file has no get function. Rename the script (and delete any __pycache__ folder next to it).
  2. A hash is calculated over exact bytes. Text mode can translate line endings and decode characters, so the bytes hashed might not be the bytes on disk — giving a hash that does not match sha256sum. Binary mode reads the file exactly as stored.
  3. No. The key remains in the repository's history, and automated scanners may already have copied it within minutes of the push. The only fix is to revoke or rotate the key at the provider immediately, then remove it from history and store secrets outside the code from then on.

Your lab

Like scripting in Bash, this needs a real Python installation, so your practice is the See it yourself section on your own machine. You have finished this lesson when all three tools run correctly and are committed to your portfolio repository.

Bonus challenge: extend failed_logins.py to also print which usernames were tried most. You will need a second Counter and the word just before from on each line.

Then revisit Challenge 04 — Decode the encoded and Challenge 08 — Decode a session cookie: both can be solved in two lines of Python with the base64 module.

→ Open Stage 1 labs


Summary in your language

தமிழ் சுருக்கம் (Tamil summary)

Security-க்கு Python ஏன்?

Bash commands-ஐ இணைக்க சிறந்தது. ஆனால் தரவை எண்ணுவது, குழப்பமான logs-ஐ கையாள்வது, websites-உடன் பேசுவது போன்ற வேலைகளுக்கு Python மிக எளிது. SOC, incident response, penetration testing — எல்லா இடங்களிலும் Python பயன்படுகிறது.

அடிப்படைகள்:

  • Variables — name = "priya", attempts = 3
  • f-string — f"{name} failed {attempts} times" — { } உள்ளே உள்ளது அதன் மதிப்பால் மாற்றப்படும்.
  • List — ips = ["10.2.14.9", "203.0.113.44"] — வரிசையான தொகுப்பு
  • Dictionary — {"name": "priya", "role": "viewer"} — பெயரால் தேடுவது
  • Indentation — Python-ல் வரியின் தொடக்க இடைவெளி தான் syntax. எப்போதும் 4 spaces.
  • Virtual environment (.venv) — ஒவ்வொரு project-க்கும் தனி packages.

இந்தப் பாடத்தில் உருவாக்கும் 3 tools:

  1. Log analyser — failed SSH logins-ஐ எண்ணி, அதிகம் தாக்கிய IP-களைக் காட்டும் (Counter).
  2. File integrity checker — SHA-256 hash மூலம் file மாற்றப்பட்டதா என்று சரிபார்க்கும்.
  3. Security header checker — ஒரு website எந்த security headers அனுப்புகிறது என்று பார்க்கும்.

கவனிக்க வேண்டிய ஆபத்துகள்:

  • pip install செய்யும்போது package பெயரை சரியாக எழுதுங்கள் — ஒரு எழுத்துப் பிழை கூட போலி package-ஐ நிறுவக்கூடும்.
  • API keys, passwords-ஐ code-ல் எழுதி GitHub-ல் போடாதீர்கள். கசிந்தால் உடனே அந்த key-ஐ ரத்து செய்யுங்கள்.
  • eval(), pickle.load() — நம்பகமற்ற தரவில் ஒருபோதும் பயன்படுத்தாதீர்கள்.
  • verify=False — HTTPS பாதுகாப்பை அணைத்துவிடும். பயன்படுத்தாதீர்கள்.

எச்சரிக்கை: உங்கள் scripts ஒரு சாதாரண request மட்டுமே அனுப்ப வேண்டும். மற்றவர்களின் systems-க்கு எதிராக பல requests அனுப்புவது அல்லது logins முயற்சிப்பது சட்டவிரோதம்.

हिंदी सारांश (Hindi summary)

Security के लिए Python क्यों?

Bash commands जोड़ने के लिए बढ़िया है। लेकिन data गिनना, बिखरे हुए logs संभालना और websites से बात करना Python में कहीं आसान है। SOC, incident response, penetration testing — हर जगह Python इस्तेमाल होता है।

बुनियादी बातें:

  • Variables — name = "priya", attempts = 3
  • f-string — f"{name} failed {attempts} times" — { } के अंदर की चीज़ उसकी value से बदल जाती है।
  • List — ips = ["10.2.14.9", "203.0.113.44"] — क्रम वाला संग्रह
  • Dictionary — {"name": "priya", "role": "viewer"} — नाम से ढूँढना
  • Indentation — Python में line की शुरुआत के spaces ही syntax हैं। हमेशा 4 spaces।
  • Virtual environment (.venv) — हर project के लिए अलग packages।

इस lesson में बनने वाले 3 tools:

  1. Log analyser — failed SSH logins गिनकर सबसे ज़्यादा हमला करने वाले IP दिखाता है (Counter)।
  2. File integrity checker — SHA-256 hash से जाँचता है कि file बदली तो नहीं।
  3. Security header checker — देखता है कि कोई website कौन से security headers भेजती है।

इन ख़तरों से बचें:

  • pip install करते समय package का नाम ठीक से लिखें — एक अक्षर की ग़लती से नक़ली package install हो सकता है।
  • API keys या passwords code में लिखकर GitHub पर मत डालें। लीक हो जाए तो तुरंत वह key रद्द करें।
  • eval() और pickle.load() — अनजान data पर कभी इस्तेमाल न करें।
  • verify=False — HTTPS की सुरक्षा बंद कर देता है। इसका इस्तेमाल न करें।

चेतावनी: आपकी scripts सिर्फ़ एक सामान्य request भेजें। किसी और के systems पर बहुत सारी requests भेजना या logins आज़माना ग़ैरक़ानूनी है।

Want this summary in Malayalam, Telugu, Kannada or another language? Tell us — the most requested languages get added next.


Stage 1 complete

You have finished Foundations. Seven lessons down, and the shift from Stage 0 is significant — you have gone from understanding concepts to operating a system and building your own tools.

What you can now do:

  • Move around a Linux system and analyse log files with pipes
  • Read permissions, spot dangerous ones, and explain how privilege escalation begins
  • Explain the TCP handshake and what each scan result actually means
  • Read a packet capture and see why unencrypted traffic is unacceptable
  • Dissect any HTTP request or response, including content types, auth headers and security headers
  • Explain how sessions work, check the three critical cookie flags, and test for fixation and broken logout
  • Write small, safe Bash scripts and Python tools that turn manual checks into repeatable ones

You can now perform real security work — session tests that appear in genuine assessment reports, an automated log summary SOC teams use daily, file integrity checks, and a header audit. You are no longer only reading.

Before moving on: make sure your portfolio has writeups for the Stage 1 labs, plus your Bash script and three Python tools. That habit is what Stage 6 depends on.

Next, make sure every Stage 0 and Stage 1 lab is solved and written up — that is the best preparation for what comes after.

→ Back to all lessons