LESSON 25 · BEGINNER5 min read

Python for Security: First Steps

Use variables, collections, functions, files, and exceptions to turn a repetitive security task into a small, reliable program.

OWASP Top 10 · MITRE ATT&CK · NIST CSF 2.0Free to readModule 6 of 14
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Write and run a Python script with functions, loops, and conditionals.
  • Choose lists, dictionaries, and sets for common security data.
  • Read a file line by line and handle malformed input without crashing.
  • Create an isolated virtual environment and install a package safely.

01Why Python Fits Security Work

Security work is full of small, repetitive data problems: parse an authentication log, count failures by address, compare two lists of users, extract URLs from an email, query an API, or turn a scanner's JSON output into a report. Python is popular because it is readable, has excellent standard-library support, and lets you move from a quick script to a tested tool without changing language.

You do not need to become a software engineer before you can automate useful work. You need four building blocks: values and variables, collections, control flow, and functions. Add file handling and exceptions, and you can solve a large proportion of everyday analysis tasks. Add a testing habit, and your scripts become trustworthy enough to reuse.

Every script in this course runs in your isolated lab. Do not point an automation script at systems you do not own. Do not embed real credentials in source code. Treat every input as untrusted: log lines can be malformed, API responses can be huge, and filenames can contain path-traversal characters. Safe automation starts with a clear boundary.

02Values, Collections, and Control Flow

Python has strings for text, integers and floats for numbers, booleans for true and false, and None for absence. Lists preserve order and allow duplicates. Tuples are immutable sequences. Dictionaries map keys to values and are ideal for counting by category. Sets store unique values and are useful for comparing indicator lists. Choose the structure that matches the question.

Conditions use if, elif, and else. Loops use for to iterate and while to repeat until a condition changes. Prefer for loops over manual index arithmetic. Use enumerate when you need both the index and the value. Use zip to walk two sequences in parallel. Keep loop bodies small and name intermediate values so the intent is readable.

Functions package a repeatable calculation. Give them clear names, accept explicit parameters, and return a result instead of printing inside the function. Printing belongs at the edge of the program where a human reads output. Returning data makes the function testable and reusable. Add type hints when the shape of the data matters; they document intent and help editors catch mistakes.

first_steps.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Files, Exceptions, and the Real World

Real input is messy. A log line may be truncated. A JSON file may be empty. A CSV row may have the wrong number of fields. A network request may time out. A robust script expects these failures and decides what to do: skip the record, count the error, or stop with a clear message.

Use a with block to open files so they close even when an exception occurs. Read line by line for large files instead of loading everything into memory. Specify an encoding such as UTF-8, and use errors='replace' only when you intentionally want to preserve progress through malformed data. When parsing JSON, catch json.JSONDecodeError and report the line or record that failed.

Raise exceptions for conditions the caller cannot ignore. Catch exceptions only when you can do something useful. A bare except that swallows every error hides bugs and makes incidents harder to investigate. Log the error, add context, and either recover or fail loudly. Security tools must not silently drop evidence.

safe_reader.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04From Script to Tool

A script becomes a tool when another person can run it without reading the source. Add a short docstring, a clear command-line interface, sensible defaults, and an error message that explains how to fix the problem. Accept a file path instead of hard-coding one. Write output in a stable format such as JSON or Markdown so it can be consumed by another process.

Keep secrets out of code and out of command history. Read credentials from environment variables or a secret manager, and never print them. Validate paths before writing: a user-supplied output directory should not be allowed to escape the intended workspace. If the tool sends network requests, set timeouts, limit retries, and respect rate limits.

The final step is testing. Start with a tiny fixture that represents the real input, then add cases for empty files, malformed lines, duplicate records, and unexpected values. You do not need a large test suite to benefit. One test that reproduces a bug is worth more than a hundred lines of untested cleverness.

LET IT CLICK

The ideas worth keeping.

  • Python is useful in security because it turns messy, repetitive data work into small, testable tools.
  • Choose collections deliberately: dictionaries for counts, sets for uniqueness, lists for order.
  • Expect malformed input and handle it explicitly; never silently discard evidence.
  • A tool is a script with clear inputs, stable output, safe defaults, and a few good tests.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Count by category

Write a Python function count_by(items, key) that accepts a list of dictionaries and a key name, and returns a dictionary mapping each value to its count. Handle missing keys by counting them as 'unknown'. Demonstrate it with three event dictionaries.

Explore a worked solution
one_possible_solution.mdCybersecurity
from collections import Counter

def count_by(items, key):
    return dict(Counter(item.get(key, 'unknown') for item in items))

events = [
    {'user': 'ana'},
    {'user': 'ben'},
    {'user': 'ana'},
    {},
]
print(count_by(events, 'user'))

Counter handles the counting, dict converts the result to a plain dictionary, and .get avoids a KeyError for missing fields.

02

Exercise 2: Read a file safely

Write a function that reads a UTF-8 text file and returns a list of non-empty, stripped lines. If the file does not exist, return an empty list and print a clear message. Explain why returning an empty list is a reasonable choice here.

Explore a worked solution
one_possible_solution.mdCybersecurity
from pathlib import Path

def read_lines(path: Path) -> list[str]:
    if not path.exists():
        print(f'input not found: {path}')
        return []
    with path.open('r', encoding='utf-8') as handle:
        return [line.strip() for line in handle if line.strip()]

print(read_lines(Path('missing.txt')))

For an optional analysis input, an empty list lets the caller continue and report zero records. For a required evidence file, failing loudly would be better. The important part is that the choice is explicit and the message explains what happened.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 4 answered
01Which Python collection is best for counting occurrences by category?
02Why use a with block when opening a file?
03What is a virtual environment for?
04Why is a bare except block dangerous?

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Completion is saved in this browser. It records reading and hands-on practice progress.