Python Basics That Matter for Security
Security professionals spend a surprising amount of time doing boring things: reading long lists, cleaning data, comparing files, counting events. Python turns those chores into a few lines you can run again and again. This lesson teaches only the parts of Python you will actually use, and it assumes you have never programmed.
Why Python, and why now
Python is readable, available on every system, and has a huge standard library. That matters in security work: you often land on a fresh machine where you cannot install anything, and Python is usually already there. Most security tools and many public training platforms are scripted in it. Think of it as a Swiss army knife for data: not the fastest tool, but always in your pocket.
A word about attitude. You will write small, boring and defensive scripts: scripts that check scope, read data, count, format and report. That is exactly what real engagements need. You will not write malware or attack code in this course, and the examples never touch a system you do not own.
Scripts do not change the law
A script that talks to a network or a website acts on your behalf, with the same legal responsibility as if you had typed each request. Only run scripts that contact systems you own or are explicitly authorized to test (your own lab, DVWA, OWASP Juice Shop, a PortSwigger lab, a TryHackMe or HackTheBox machine). In France, articles 323-1 to 323-3-1 of the Code pénal apply to the person who runs the code.
Setting up
Install a recent Python 3 on your host machine or in your Kali virtual machine. Check it works by opening a terminal and typing:
python3 --version
python3
The second command opens an interactive prompt (the "REPL") where you can type code and see the result immediately. Type exit() to leave. For real work you will write code in a file ending with .py and run it with python3 myscript.py.
Good habit from day one: create a virtual environment per project. It keeps the libraries of one project separate from those of another.
python3 -m venv .venv
source .venv/bin/activate
In this course we will only use the standard library, so you will not need to install anything else.
Variables and basic types
A variable is a labeled box that holds a value. Python figures out the type by itself.
host = "lab-srv01" # text (a string)
port = 8080 # a whole number (int)
is_in_scope = True # True or False (a boolean)
ratio = 0.75 # a decimal number (float)
Text can be combined with values using an f-string, a string that starts with f and puts variables between braces:
print(f"Checking {host} on port {port}")
Lists and dictionaries
A list is an ordered collection, like a shopping list. A dictionary stores pairs of key and value, like a phone book.
hosts = ["lab-srv01", "lab-srv02", "lab-ws01"]
hosts.append("lab-dc01")
print(len(hosts)) # 4
print(hosts[0]) # first item
service = {"host": "lab-srv01", "port": 8080, "name": "web"}
print(service["port"]) # 8080
Most security data has this shape: a list of things, each described by a dictionary (a host, its open ports, its software). Remember that picture, you will use it constantly.
Decisions and loops
Use if to decide and for to repeat. Python uses indentation (four spaces) to know which lines belong together. This is not cosmetic: a wrong indent changes the meaning.
for host in hosts:
if host.startswith("lab-ws"):
print(f"{host} is a workstation")
else:
print(f"{host} is a server")
Functions: small reusable tools
A function gives a name to a piece of logic so you can reuse and test it.
def is_web_port(port):
return port in (80, 443, 8080, 8443)
print(is_web_port(443)) # True
print(is_web_port(22)) # False
Rule of thumb: if you copy and paste the same lines twice, turn them into a function.
Reading and writing files
Security data usually lives in text files. The safe way to open a file is with a with block, which closes it automatically:
with open("hosts.txt", encoding="utf-8") as f:
lines = f.read().splitlines()
print(f"{len(lines)} lines read")
To write a result:
with open("report.txt", "w", encoding="utf-8") as f:
for line in lines:
f.write(line.upper() + "\n")
The "w" mode creates the file or overwrites it. Be careful not to overwrite your only copy of evidence.
Handling errors without crashing
Real data is messy: a file may be missing, a line may be empty. A try / except block lets your program handle a problem instead of crashing with a long message.
try:
with open("hosts.txt", encoding="utf-8") as f:
lines = f.read().splitlines()
except FileNotFoundError:
print("hosts.txt not found, create it first")
lines = []
Where to find help
The official Python documentation and the built-in help() function are your best friends: type help(str.split) in the REPL to read about a method. When you search online, always read an answer before running it, especially if it downloads something or runs system commands. Never paste commands you do not understand into a terminal.
Your turn: write your first helper
Create a file basics.py with a function classify_port(port) that returns "web" for ports 80, 443, 8080 and 8443, "remote-admin" for 22 and 3389, and "other" for anything else. Then loop over the list [22, 80, 3389, 5432, 8443] and print one line per port, such as 22 -> remote-admin.
See a solution
def classify_port(port):
if port in (80, 443, 8080, 8443):
return "web"
if port in (22, 3389):
return "remote-admin"
return "other"
for port in [22, 80, 3389, 5432, 8443]:
print(f"{port} -> {classify_port(port)}")
Expected output: five lines, 22 -> remote-admin, 80 -> web, 3389 -> remote-admin, 5432 -> other, 8443 -> web. If you got an indentation error, check that the lines under def and if start with the same number of spaces.
Portfolio step
Create a folder 02-python-security in your portfolio. Save basics.py and write a three-line README that states: what the script does, how to run it, and "for educational use on systems I own or am authorized to test". Starting every project with that sentence is a professional habit.
Key takeaways
- Python is readable, widely available and perfect for chores such as reading, cleaning and counting data.
- Variables, lists, dictionaries, loops, functions and files cover most of what you will need.
- Use
with open(...)for files andtry/exceptfor predictable errors. - Work in a virtual environment and read any code before you run it.
- A script carries your legal responsibility: only target systems you own or are authorized to test.
In the next lesson you will use these building blocks to automate a small reconnaissance chore, with a safety check built in.