Python from Scratch
Almost every tool you’ll use is written in Python, and sooner or later one won’t do exactly what you need: you’ll have to read its code, change a line or write your own script. This card is for people who have never programmed. By the end you’ll be able to write a small program that reads a file, processes it, takes command-line options and doesn’t fall over at the first problem. The offensive side (HTTP requests, sockets, exploits) comes in the next card.
Concepts
Section titled “Concepts”Running Python
Section titled “Running Python”There are two ways to use it. The interactive interpreter (type python3 and you get >>>) runs each line when you press Enter: ideal for trying something in ten seconds. A script is a .py file you run as a whole with python3 script.py.
On Kali and almost any current Linux the command is python3. Plain python may not exist or, on old systems, may point to Python 2, which has been dead since 2020 and behaves differently. Always use python3.
If the script’s first line is a shebang and you make it executable, you can run it like any other program:
#!/usr/bin/env python3print("hello")chmod +x hello.py./hello.pyVariables and types
Section titled “Variables and types”A variable is a name that points to a value. You don’t declare the type: Python works it out from the value.
| Type | Example | Used for |
|---|---|---|
int |
port = 445 |
Whole numbers |
float |
timeout = 0.5 |
Numbers with decimals |
str |
host = "10.10.10.5" |
Text |
bool |
is_open = True |
True or false |
None |
response = None |
“No value yet” |
Types don’t mix on their own: "port " + 22 is an error. You have to convert: str(22), int("8080"), float("0.5"). Watch division: 7 / 2 is 3.5, 7 // 2 is 3 (integer division) and 7 % 2 is 1 (the remainder).
In an if, every “empty” value counts as false: 0, "", [], {} and None. Anything else counts as true, including the text "0".
Text (str)
Section titled “Text (str)”The type you’ll use most: paths, IPs, server responses, credentials.
- f-strings to put variables inside text:
f"[+] {host}:{port} open". - Slicing to take a piece:
s[:5](first five),s[-1](last),s[::-1](reversed). Indexes start at 0. - Methods you’ll use daily:
strip()(removes spaces and newlines from both ends),split(":")(splits into a list),":".join(items)(the opposite),replace(),lower()/upper(),startswith(),endswith(), and theinoperator to look for a substring.
The four structures
Section titled “The four structures”| Structure | Syntax | Ordered | Changeable | Duplicates | Use it for |
|---|---|---|---|---|---|
| List | [22, 80, 443] |
Yes | Yes | Yes | A collection you keep filling |
| Tuple | ("10.10.10.5", 80) |
Yes | No | Yes | A fixed group of values that belong together |
| Dictionary | {"ssh": 22, "http": 80} |
Yes (insertion order) | Yes | Unique keys | Looking up a value by name |
| Set | {22, 80} |
No | Yes | No | Removing duplicates and comparing collections |
- List:
ports.append(8080),ports[0],len(ports),sorted(ports). - Tuple: often used to “unpack”:
ip, port = ("10.10.10.5", 80). - Dictionary:
d["ssh"]fails if the key doesn’t exist;d.get("ftp")returnsNoneandd.get("ftp", 21)returns the default.d.items()gives the key-value pairs to loop over. - Set:
set(items)removes duplicates;a & bis what they share,a | bthe union anda - bwhat’s inabut not inb.
Control flow
Section titled “Control flow”Python marks blocks with indentation (4 spaces), not braces. Whatever sits below an if or a for and is indented belongs to it.
if status == 200: print("exists")elif status in (301, 302): print("redirects")else: print("nothing")
for port in [22, 80, 443]: print(port)
for i in range(1, 4): # 1, 2, 3 (the end is not included) print(i)
for n, port in enumerate([22, 80, 443], start=1): print(n, port) # loop number and item at once
attempts = 0while attempts < 3: attempts += 1break leaves the loop and continue jumps to the next iteration. A list comprehension condenses a for that builds a list: [p for p in ports if p < 1024].
Functions and modules
Section titled “Functions and modules”A function packages a piece of code under a name so you can reuse it. It takes parameters, can have default values and returns a result with return (without return, it returns None).
def url(host, port=80, https=False): scheme = "https" if https else "http" return f"{scheme}://{host}:{port}/"
url("10.10.10.5") # 'http://10.10.10.5:80/'url("10.10.10.5", 443, https=True) # 'https://10.10.10.5:443/'A module is a Python file with functions you can import. The standard library ships many: import sys, import os, from pathlib import Path. Third-party ones (like requests) are installed with pip.
The if __name__ == "__main__": block at the end of a script means “run this only when this file is launched directly, not when another file imports it”. You’ll see it in almost every exploit.
Files and errors
Section titled “Files and errors”To read or write a file, use with open(...), which closes it for you even if something fails along the way:
with open("ips.txt", encoding="utf-8") as f: for line in f: print(line.strip())
with open("output.txt", "w", encoding="utf-8") as f: # "w" overwrites, "a" appends f.write("10.10.10.5\n")When something goes wrong, Python raises an exception and, if nobody catches it, the program stops with a traceback. Read it from the bottom up: it tells you what happened and on which line. With try/except you decide what to do instead of crashing:
| Exception | When it fires |
|---|---|
FileNotFoundError |
The file doesn’t exist |
ValueError |
The value doesn’t make sense: int("abc") |
TypeError |
Types that don’t fit: "a" + 1 |
KeyError |
A key that isn’t in the dictionary |
IndexError |
A position outside the list |
finally always runs, error or not: use it for cleanup.
Command-line options and environments
Section titled “Command-line options and environments”argparse turns your script into a tool with options and automatic help (-h), like any Kali program.
Third-party libraries are installed with pip, always inside a virtual environment (a folder with its own Python and its own libraries, isolated from the system):
python3 -m venv .venv # create the environmentsource .venv/bin/activate # activate it (the prompt shows (.venv))pip install requests # install only herepip freeze > requirements.txt # record what's installedpip install -r requirements.txt # rebuild the environment on another machinedeactivate # leave itIn practice
Section titled “In practice”A script that grows through the card: it reads a file of IPs (one per line), skips comments and empty lines, validates each IP, counts repeats and, optionally, filters by prefix and saves the unique ones.
10.10.10.510.10.10.7# comment
10.10.10.5192.168.56.2010.10.10.300#!/usr/bin/env python3import argparseimport ipaddressimport sys
def is_valid_ip(text): try: ipaddress.ip_address(text) # raises ValueError if it isn't an IP return True except ValueError: return False
def read_ips(path): ips = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue # skip empty lines and comments ips.append(line) return ips
def main(): parser = argparse.ArgumentParser(description="Count and filter IPs from a file") parser.add_argument("file", help="file with one IP per line") parser.add_argument("-p", "--prefix", default="", help="only IPs starting with this") parser.add_argument("-o", "--output", help="save the unique IPs to this file") args = parser.parse_args()
try: ips = read_ips(args.file) except FileNotFoundError: print(f"[!] Not found: {args.file}", file=sys.stderr) sys.exit(1)
valid = [ip for ip in ips if is_valid_ip(ip)] invalid = [ip for ip in ips if not is_valid_ip(ip)] unique = sorted(set(valid)) if args.prefix: unique = [ip for ip in unique if ip.startswith(args.prefix)]
counts = {} for ip in valid: counts[ip] = counts.get(ip, 0) + 1
print(f"Read: {len(ips)} · valid: {len(valid)} · unique: {len(unique)}") for ip in unique: print(f" {ip:<15} x{counts[ip]}") for ip in invalid: print(f" [discarded] {ip}")
if args.output: with open(args.output, "w", encoding="utf-8") as f: f.write("\n".join(unique) + "\n") print(f"[+] Saved to {args.output}")
if __name__ == "__main__": main()$ python3 count.py ips.txtRead: 5 · valid: 4 · unique: 3 # 5 useful lines; 10.10.10.300 is not an IP 10.10.10.5 x2 # {ip:<15} pads to 15 characters 10.10.10.7 x1 192.168.56.20 x1 [discarded] 10.10.10.300
$ python3 count.py ips.txt -p 10.10 -o targets.txtRead: 5 · valid: 4 · unique: 2 10.10.10.5 x2 10.10.10.7 x1 [discarded] 10.10.10.300[+] Saved to targets.txt
$ python3 count.py missing.txt[!] Not found: missing.txt # caught: clear message and exit code 1
$ python3 count.py -husage: count.py [-h] [-p PREFIX] [-o OUTPUT] file # argparse writes the help for youNotice what each part uses: a list for the IPs read, a set to remove duplicates, a dictionary to count, functions to split up tasks, with for the file, try/except for two different errors and argparse for the options.
Next offensive step
Section titled “Next offensive step”With this you can already read and modify other people’s scripts. The next card applies the same to security: HTTP requests with requests (and routing them through Burp), sockets to talk to any service, running commands with subprocess and adapting public exploits, which is where the difference between str and bytes really shows.
- Offensive Python
- Bash scripting, for when the job fits in one line
- Regular expressions, to search text for patterns from Python
Cheat sheet
Section titled “Cheat sheet”| Concept | What to remember |
|---|---|
python3 |
Always python3; Python 2 is dead |
| Types | int, float, str, bool, None; convert with int(), str() |
/ · // · % |
Division with decimals · integer division · remainder |
| Empty = false | 0, "", [], {}, None |
| f-string | f"{host}:{port}" |
| Slicing | s[:5], s[-1], s[::-1]; indexes from 0 |
| List · tuple | Changeable · fixed |
| Dictionary | d.get(key, default) doesn’t fail if missing |
| Set | set() removes duplicates; &, | and - |
| Indentation | 4 spaces define the block |
range(a, b) |
From a to b-1 |
enumerate() |
Loop number and item |
with open() |
Closes the file for you; "w" overwrites, "a" appends |
try/except |
Catch specific exceptions, not all of them |
if __name__ == "__main__": |
Only runs when the file is launched directly |
argparse |
Options and -h for free |
venv |
One environment per project; never sudo pip |
pipx |
Isolated command-line tools |
Review questions
Section titled “Review questions”- Why does
"port " + 22fail, and how do you fix it?
Answer
Because Python doesn’t mix types on its own: it can’t add text and a number (TypeError: can only concatenate str (not "int") to str). Convert the number: "port " + str(22), or better an f-string: f"port {22}".
- You have a list of IPs with repeats and want the unique ones, sorted. What do you write?
Answer
sorted(set(ips)). set() removes duplicates (but has no order) and sorted() returns a sorted list.
- What’s the difference between
d["ftp"]andd.get("ftp", 21)when the key doesn’t exist?
Answer
d["ftp"] raises KeyError and, if you don’t catch it, the program stops. d.get("ftp", 21) returns 21 with no error.
- What does
for i in range(1, 4): print(i)print?
Answer
1, 2 and 3. The end of range is not included.
- Why use
with open(...)instead off = open(...)?
Answer
Because with closes the file automatically when the block ends, even if an exception happens halfway. With a bare open() you have to remember f.close(), and if something fails first the file stays open.
- A function
def add(x, items=[])returns[1]the first time and[1, 2]the second. Why?
Answer
The default [] is created only once, when the function is defined, and reused on every call. Since lists can be modified, it keeps growing. The correct form is items=None and inside if items is None: items = [].
- On Kali,
pip install requestsfails withexternally-managed-environment. What do you do?
Answer
Create and activate a virtual environment (python3 -m venv .venv and source .venv/bin/activate) and install there. If it’s a command-line tool you want globally, pipx install. Don’t use sudo pip or --break-system-packages.
- What is
if __name__ == "__main__":for?
Answer
So that the code inside only runs when you launch that file directly (python3 script.py), not when another script imports it to use its functions.