Python Basics for Security, Explained
If you are reading this, you have probably been told "learn a bit of Python" for security work, and you want to know what to learn first and what you will actually use it for.
By the end you will be able to run a Python script, use its basic building blocks (values, lists, dictionaries, loops, functions, errors), read a log file and count what matters in it, hash a file, and avoid the handful of mistakes that make security scripts themselves vulnerable. You do not need to have programmed before. You do need a terminal, so read Linux Fundamentals first if that is new to you.
Why Python? Google's Cybersecurity Certificate has a whole course called "Automate Cybersecurity Tasks with Python" (Google Career Certificates), and a core knowledge unit in the US government's list of cyber defense degree topics is called "Basic Scripting and Programming" (NCAE-C CAE-CD Knowledge Units). In practice, Python is how analysts turn a repeated manual task, such as counting failed logins across a thousand lines, into a script.
1. Set up and run your first script
Check whether Python 3 is installed:
python3 --version
If you see a version number you are ready. If not, download it from python.org. The examples here were tested on Python 3.9 and 3.12, so any recent Python 3 will do.
There are two ways to use Python:
- Interactively: type
python3and press Enter to get a prompt (>>>) where each line runs at once. Typeexit()to leave. - As a script: save code in a file ending in
.pyand runpython3 myscript.py.
Create a small folder for practice, and use a virtual environment for any project that installs packages. The Python documentation describes it as a lightweight environment with its own independent set of packages, by default isolated from the packages installed system-wide (venv):
mkdir pylab && cd pylab
python3 -m venv .venv
source .venv/bin/activate # macOS and Linux; Windows uses a different activation command
python --version
deactivate # leave the environment when you are done
The examples in this post use only Python's built-in library, so they need no installs.
2. The building blocks
Open the interactive prompt (python3) and try these. Lines starting with # are comments, ignored by Python.
Values and variables
A variable is a name for a value. Text is a str, whole numbers are int, true/false is bool.
name = "alice"
attempts = 3
print(f"{name} tried {attempts} times") # an f-string puts values into text
# alice tried 3 times
The type matters. "1" + "1" joins two pieces of text and gives "11", while 1 + 1 gives 2. Confusing the two is a common source of bugs, and a common source of security bugs when text from a user is used as a number.
Lists, sets and dictionaries
ips = ["192.0.2.10", "203.0.113.5", "192.0.2.10"] # a list keeps order and duplicates
print(len(ips)) # 3
print(sorted(set(ips))) # a set removes duplicates
# ['192.0.2.10', '203.0.113.5']
counts = {} # a dictionary maps a key to a value
for ip in ips: # a loop repeats for each item
counts[ip] = counts.get(ip, 0) + 1
print(counts)
# {'192.0.2.10': 2, '203.0.113.5': 1}
(The addresses in this post come from blocks that RFC 5737 reserves for examples, so none of them belongs to a real machine.)
The dictionary pattern "count how many times each thing appears" is the most useful trick in log analysis, and Python's standard library already has a tool for it, collections.Counter, which its documentation describes as "a dict subclass for counting hashable objects" (collections).
Indentation, decisions and functions
Python uses indentation (spaces at the start of a line) to show which lines belong together. A function is a named, reusable block.
def risk(failures):
if failures >= 5:
return "high"
elif failures >= 2:
return "medium"
return "low"
print(risk(6), risk(2), risk(0))
# high medium low
Errors
When something goes wrong Python raises an exception. You can catch it so the script does not crash on bad input:
try:
int("abc")
except ValueError as e:
print("error:", e)
# error: invalid literal for int() with base 10: 'abc'
For security tools, handling unexpected input is part of the job, because the data you read (logs, files, network replies) may be malformed or deliberately hostile.
Modules
Python ships with a large standard library. You bring in a module with import. Throughout this post you will use csv, collections, hashlib, secrets, subprocess, os, socket and ipaddress, all built in.
3. Project 1: find brute force and spraying in a login log
This repeats the investigation from SQL Basics for Security, this time in Python. Save this as logins.csv:
ts,username,source_ip,success
2026-11-05 09:00:11,alice,192.0.2.10,1
2026-11-05 09:02:40,bob,192.0.2.11,0
2026-11-05 09:02:52,bob,192.0.2.11,1
2026-11-05 09:15:03,carol,192.0.2.12,1
2026-11-05 10:01:00,admin,203.0.113.5,0
2026-11-05 10:01:02,admin,203.0.113.5,0
2026-11-05 10:01:04,admin,203.0.113.5,0
2026-11-05 10:01:06,admin,203.0.113.5,0
2026-11-05 10:01:08,admin,203.0.113.5,0
2026-11-05 10:01:10,admin,203.0.113.5,0
2026-11-05 11:30:00,alice,198.51.100.7,0
2026-11-05 11:30:30,bob,198.51.100.7,0
2026-11-05 11:31:00,carol,198.51.100.7,0
2026-11-05 11:31:30,admin,198.51.100.7,0
2026-11-05 11:32:00,dave,198.51.100.7,0
2026-11-05 12:10:00,,192.0.2.99,0
Then save this as analyze_logins.py:
import csv
from collections import Counter, defaultdict
failures = Counter() # source_ip -> number of failed attempts
usernames = defaultdict(set) # source_ip -> set of usernames it tried
with open("logins.csv", newline="") as f:
for row in csv.DictReader(f):
if row["success"] == "0":
ip = row["source_ip"]
failures[ip] += 1
if row["username"]: # an empty string counts as "no username"
usernames[ip].add(row["username"])
for ip, count in failures.most_common():
tried = len(usernames[ip])
if count >= 5 and tried == 1:
verdict = "looks like brute force (many guesses, one account)"
elif count >= 4 and tried >= 4:
verdict = "looks like password spraying (one guess each, many accounts)"
else:
verdict = "no pattern"
print(f"{ip:<14} failures={count} usernames={tried} {verdict}")
Run it with python3 analyze_logins.py:
203.0.113.5 failures=6 usernames=1 looks like brute force (many guesses, one account)
198.51.100.7 failures=5 usernames=5 looks like password spraying (one guess each, many accounts)
192.0.2.11 failures=1 usernames=1 no pattern
192.0.2.99 failures=1 usernames=0 no pattern
What each part does:
| Line | Purpose |
|---|---|
csv.DictReader(f) |
Reads each row of the CSV file as a dictionary keyed by the header names. See the csv module |
with open(...) as f |
Opens the file and closes it automatically when the block ends |
Counter, .most_common() |
Counts per address and lists the biggest first |
defaultdict(set) |
A dictionary that starts each missing key with an empty set, used here to collect the distinct usernames per address |
if row["username"] |
In a CSV file, a missing username is an empty string, not NULL as in the database |
The pattern logic is the same as in the SQL version, and so is the caution: these thresholds suit a tiny practice file. Real investigations also look at time windows, shared addresses and attackers who rotate addresses. Brute Force vs Password Spraying explains the attacks themselves.
4. Project 2: hash a file
Cryptography Basics explained hashes. In Python the hashlib module does the work. This script reads the file in chunks, so it also works on files too big for memory:
import hashlib
import sys
def sha256_of(path):
h = hashlib.sha256()
with open(path, "rb") as f: # "rb": read raw bytes
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
if len(sys.argv) != 2:
sys.exit("usage: python3 hash_file.py FILE")
print(sha256_of(sys.argv[1]), sys.argv[1])
Save it as hash_file.py, then:
printf 'Hello, world\n' > hello.txt
python3 hash_file.py hello.txt
# 37980c33951de6b0e450c3701b219bfeee930544705f637cd1158b63827bb390 hello.txt
That is the same value shasum -a 256 hello.txt and openssl dgst -sha256 hello.txt print for the same file, which is a good way to check your script. (Python 3.11 and newer also have a helper, hashlib.file_digest, for this job, per the hashlib documentation; the loop above works on older versions too.)
Two real uses: checking a download against the hash its publisher lists, and finding whether a suspicious file's hash matches a known one (an indicator of compromise, see Threat Intelligence and OSINT).
5. Project 3: check your own machine's ports
A port is a numbered door on a computer where a program listens (see Computer and Networking Basics). This script tries to connect to two ports on your own computer (127.0.0.1):
import socket
def is_open(host, port):
with socket.socket() as s:
s.settimeout(1)
return s.connect_ex((host, port)) == 0 # 0 means the connection succeeded
for port in (8000, 8001):
print(port, "open" if is_open("127.0.0.1", port) else "closed")
In a second terminal start Python's built-in web server on only your own machine: python3 -m http.server 8000 --bind 127.0.0.1. Run the script and you see:
8000 open
8001 closed
Stop the server (press Ctrl+C in its terminal) and run the script again: both ports show closed. You have written the core idea of a port scanner.
Boundary: only ever point a script like this at systems you own or have written permission to test. Scanning other people's machines can be illegal and is covered in Security Testing. Tools such as Nmap do this far better than a ten-line script; the point of writing it is to understand what they do.
6. Writing security scripts that are not themselves vulnerable
Security scripts often process untrusted data, so their own mistakes matter. These are the habits to learn early.
Use secrets, not random, for anything secret
Python's random module is for simulations. Its documentation says: "The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module" (random). The secrets module is "used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets" (secrets).
import secrets
print(secrets.token_urlsafe(16)) # for session IDs, reset links, API tokens
print(secrets.token_hex(16)) # the same idea, shown as hexadecimal
Each run prints different random values. This is how you would generate a token for a password-reset link.
Never put secrets in the script
Passwords and API keys written into source code get copied, shared and pushed to repositories (see Git and GitHub, which explains what to do first if that happens). Read them from the environment instead:
import os
api_key = os.environ.get("LAB_API_KEY")
if api_key is None:
raise SystemExit("LAB_API_KEY is not set")
print("key loaded, length", len(api_key))
python3 env_secret.py # LAB_API_KEY is not set
LAB_API_KEY=abc123 python3 env_secret.py # key loaded, length 6
Environment variables are a step up from hard-coding, not a perfect vault: other processes of the same user may be able to read them, and they can leak into logs. Larger systems use dedicated secrets services.
Never glue user input into a shell command
This is the command-line version of SQL injection. The subprocess documentation says the library "will not implicitly choose to call a system shell", but that "if the shell is invoked explicitly, via shell=True, it is the application's responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities" (subprocess, Security Considerations). See it happen:
import subprocess
user_input = "report.txt; echo INJECTED" # what an attacker might type
print("--- unsafe: shell=True with glued-together text", flush=True)
subprocess.run("echo checking " + user_input, shell=True)
print("--- safer: a list of arguments, no shell", flush=True)
subprocess.run(["echo", "checking", user_input])
--- unsafe: shell=True with glued-together text
checking report.txt
INJECTED
--- safer: a list of arguments, no shell
checking report.txt; echo INJECTED
In the unsafe version the ; ended one command and started another, so the attacker's echo INJECTED ran. In the safe version the whole input stayed one argument. The rule is the same as for databases: keep code and data separate.
Never eval() or unpickle untrusted data
eval(): the Python documentation warns "This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities" (built-in functions). If you only need to read a Python-style value such as a list or number,ast.literal_evalaccepts just literals such as strings, numbers, lists and dictionaries, not arbitrary expressions (ast).pickle: "The pickle module is not secure. Only unpickle data you trust. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling." The same page suggests that "safer serialization formats such as json may be more appropriate if you are processing untrusted data" (pickle).
Prefer the standard library to hand-written checks
Suppose you write your own test for private addresses:
def is_private(ip):
return ip.startswith("10.") or ip.startswith("192.168.")
It looks right, but it misses 172.16.0.5, which is also a private address. Python's ipaddress module knows the real rules:
import ipaddress
print(ipaddress.ip_address("172.16.0.5").is_private) # True
print(ipaddress.ip_address("8.8.8.8").is_private) # False
The documentation says is_private is "True if the address is defined as not globally reachable" by the IANA special-purpose registry, with a few listed exceptions (ipaddress). Note what that means: the example addresses used in this post, which are reserved for documentation, are also reported as private by this definition. Test your own code against such details.
Be careful what you install
Packages from the Python Package Index are other people's code, run with your privileges. Fake packages with names close to popular ones are a real risk (see Typosquatting). Check the exact name and publisher before installing, install into a virtual environment, and keep the number of dependencies small. Likewise, when your own script makes secure connections, use the library's secure defaults: Python's ssl.create_default_context() is documented as returning "a new context with secure default settings" (ssl).
7. Practise safely
- Re-type each script yourself rather than pasting it. Break it on purpose (remove a colon, rename a variable) and read the error message.
- Extend
analyze_logins.pyto also print the first and last timestamp for each address that has failures. - Make it list addresses that have failures and at least one success. (Compare with the SQL version of the same question.)
- Write a script that takes a directory, hashes every file in it with
sha256_of, and prints the results. Compare a few againstshasum -a 256. - Generate 10 tokens with
secrets.token_urlsafe(24). Then explain why you would not userandom.choicefor them. - Only run scripts against data and systems you own or are authorised to test.
8. Common mistakes
| Mistake | The facts |
|---|---|
"random is fine for tokens" |
Its documentation says not to use it for security. Use secrets |
| "I'll hard-code the API key for now" | Code gets copied and pushed. Read secrets from the environment or a secrets service |
"shell=True is easier" |
It makes you responsible for escaping every character. Pass a list of arguments instead |
"eval is a quick way to parse input" |
It runs arbitrary code. Use json or ast.literal_eval |
"pickle is a handy file format" |
Unpickling untrusted data can run attacker code. Use JSON for untrusted data |
| "I'll write my own parser/checker" | The standard library already handles edge cases such as 172.16.0.5 |
| "My script found nothing, so there's no attack" | A script only finds the pattern you coded. Thresholds and assumptions matter |
| "I'll install whatever package I find" | Check names and publishers, and use a virtual environment |
| "Spaces and tabs don't matter" | Indentation is part of Python's syntax. Be consistent |
| "A port scanner script is harmless" | Scanning systems you do not own can be illegal. Stay on 127.0.0.1 or authorised targets |
Closing
You do not need to become a software developer to use Python in security. Learn the building blocks, read a file, count what matters, hash what you need to verify, and write scripts as carefully as you would want the tools you use to be written.
Keep these points:
- Run scripts and use the interactive prompt. Use a virtual environment for projects with packages.
- The building blocks: values, lists, sets, dictionaries, loops, functions and exceptions.
csvplusCounterturns a log file into answers about who is attacking what.hashlibin chunks hashes any file and matchesshasumandopenssl.secrets, notrandom, for anything an attacker must not guess.- No secrets in code; read them from the environment.
- Never glue input into shell commands,
eval, or unpickle untrusted data. - Prefer the standard library to hand-written checks.
- Stay on systems you own or are authorised to test.
If you can read a log with a script, say what it found and what it could not, and explain why shell=True with user input is dangerous, you are ready for the next steps.
Related: SQL Basics for Security does the same log analysis in a database, Cryptography Basics explains the hashes and tokens used here, and Linux Fundamentals covers the terminal and the shell scripts that Python often replaces.