Notes
Parse a log
First, the same job as the Bash episode, in Python. A regular expression describes the line we care about and captures the user and the address. A Counter keeps the tally. The loop reads the file one line at a time, so it works on a log of any size without loading it into memory. Most common three prints the top three. On our practice log it reports the same result: four hundred and twelve failures from one address.
import re, collections
pat = re.compile(r"Failed password for"
r" (?:invalid user )?(\S+) from (\S+)")
hits = collections.Counter()
with open("auth.log") as f:
for line in f:
m = pat.search(line)
if m:
hits[m.group(2)] += 1
print(hits.most_common(3)) Why Python here
Why bother, when Bash did this in one line? Because the count is now data you can reason about. You can apply a threshold, compare against an allow list of your own office addresses, look each address up in a reputation service, and decide what to do, all in the same script with proper error handling. On the practice log, two addresses pass the threshold of fifty. That decision step is where Python earns its place.
for ip, n in hits.most_common():
if n >= 50:
print("block", ip, n)
# output on the practice log
block 203.0.113.9 412
block 198.51.100.23 87
# next: check each against an
# allow list, a geo lookup, an API hashlib
Next, hashing. A hash is a fingerprint of a file's contents. This function reads the file in chunks, so it can hash something larger than memory, and returns the SHA two fifty six value. Security engineers use it constantly: to verify that a download is the file the vendor published, to detect that a system file has changed, and to look a suspicious file up in a malware database without uploading the file itself.
import hashlib
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(
lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
# use: verify downloads, detect
# changed files, look up malware ipaddress
Addresses are not strings, and comparing them as strings causes bugs. The ipaddress module understands them. You can ask whether an address is private, and whether it falls inside a network range. That turns questions like is this login from inside the company, or is this destination in a range we have blocked, into one clear line. Both checks here return true for our practice data.
import ipaddress as ipa
ipa.ip_address("10.0.0.9").is_private
# True
net = ipa.ip_network("203.0.113.0/24")
ipa.ip_address("203.0.113.9") in net
# True
# is this source internal?
# is it inside a blocked range? requests
Nearly every security product, cloud and code platform is driven through a web API, and the requests library is how Python talks to them. Four habits are visible in this snippet. The token comes from an environment variable, never from the source code. There is a timeout, so a hung server cannot hang your script. Raise for status turns an error response into an exception instead of silent bad data. And certificate checking stays on, always.
import os, requests
r = requests.get(
"https://api.example/v1/findings",
headers={"Authorization":
"Bearer " + os.environ["TOKEN"]},
params={"severity": "critical"},
timeout=10)
r.raise_for_status()
for f in r.json()["items"]:
print(f["id"], f["title"]) socket
Sometimes you need to go one level below HTTP. The socket module opens raw network connections. This small function tries to connect to a host and port and reports whether it worked: connect ex returns zero on success and an error number otherwise, such as one hundred and eleven for connection refused. It is the building block of the port scanner you write in the next episode, and of quick checks like is our database port reachable from here?
import socket
def is_open(host, port):
s = socket.socket()
s.settimeout(1)
try:
return s.connect_ex(
(host, port)) == 0
finally:
s.close()
# 0 = connected; an error code
# such as 111 = refused JSON and exit codes
A security script is rarely the last step. Something else consumes its output: a pipeline, a ticket system, a chat alert. So print structured output, usually JSON, which every tool can read. And set the exit code: zero when all is well, non-zero when something was found. That one convention is how a script becomes a gate in a build pipeline, because the pipeline stops when a step exits with an error.
import json, sys
result = {"ip": "203.0.113.9",
"failed": 412}
print(json.dumps(result))
# {"ip": "203.0.113.9", "failed": 412}
sys.exit(1 if findings else 0)
# a non-zero exit code fails
# the pipeline step More modules
A few more modules complete the kit. Argparse for command-line options. Pathlib for files. Subprocess to run other programs, always with the arguments as a list, never as one shell string built from outside input. The csv and json modules for common formats. Logging instead of print statements for anything you will run unattended. Datetime, in UTC, because investigations cross time zones. The cloud libraries and scapy get their own episodes.
- argparse: command-line options
- pathlib: files and folders
- subprocess: run a command (pass a list, never shell=True with outside input)
- csv, json: common formats
- logging: not print, for tools
- datetime: use UTC
- boto3 / cloud SDKs (episode 6)
- scapy: packets (episode 4)
Scripts with power
One more thing separates a security engineer's scripts. They often hold powerful credentials, so write them as if they matter. Secrets come from the environment or a secret manager, never the file. Use a read-only token unless the script truly must write. Give anything that changes things a dry-run mode. Validate input and stop on anything unexpected. Pin your dependencies, because a malicious package runs with your script's access. And log what it did.
- secrets from the environment or a secret manager, never in the file or in git
- least privilege: a read-only token unless it must write
- a --dry-run flag for anything that changes things
- validate input; fail closed
- pin and review dependencies
- log what it did
Common mistakes
Mistakes. An API key pasted into the source and pushed to git. Certificate checking switched off. No timeout. Running shell commands built from outside input, which is command injection in your own tool. Reading a ten gigabyte log into memory. Catching every exception and ignoring it, so failures are silent. Installing a package under a mistyped name, which attackers register on purpose. And no dry-run mode on a script that deletes or blocks things.
- API keys in the source
- verify=False
- no timeout
- shell=True with user input
- reading a huge file into memory
- bare except: pass
- installing packages by a mistyped name
- no dry run on destructive actions
Say it like this
In the interview: I use Python to automate what I would otherwise do by hand. Parsing logs with regular expressions and counters, hashing files, calling the APIs of security tools and clouds with requests, and small network checks with sockets. I keep secrets out of the code, use timeouts and least-privilege tokens, add a dry-run mode for anything destructive, and emit JSON with proper exit codes so the script fits into a pipeline. Then describe one script you actually wrote.
- "For automation: parsing logs
- with re and Counter, hashing
- with hashlib, calling tool and cloud APIs with requests, and small network checks with socket. I keep secrets out of code, use timeouts and least-privilege tokens, emit
- JSON and exit codes so it
- fits a pipeline."