Python for Hacking
Knowing Python is not the same as knowing how to use it on an engagement. In hacking you rarely write big programs: you write 30-line scripts that talk to a service, automate a request you would otherwise send a hundred times in Burp, or adapt a public exploit that doesn’t work on the first try. This card covers exactly that: the pieces that come up again and again, and the mistakes that cost hours.
Concepts
Section titled “Concepts”bytes and str
Section titled “bytes and str”Python 3 has two distinct types for what Python 2 treated as one:
| Type | What it is | Example |
|---|---|---|
str |
Text: Unicode characters | "admin", "ñ" |
bytes |
Raw octets, values 0–255 | b"admin", b"\x90\x90" |
You convert between them by encoding and decoding:
"ñ".encode() # b'\xc3\xb1' str -> bytes (UTF-8 by default)b"\xc3\xb1".decode() # 'ñ' bytes -> strb"\xff".decode("latin-1") # 'ÿ' latin-1 never fails: one byte, one character"c3b1" == "ñ".encode().hex() # True hex to look at bytes readablybytes.fromhex("c3b1") # b'\xc3\xb1'Sockets, files opened in "rb"/"wb" mode and almost everything that ends up in a memory exploit work in bytes. Mixing the two types produces the most common error when porting code: TypeError: can't concat str to bytes.
Memory addresses with struct
Section titled “Memory addresses with struct”In binary exploitation you have to write addresses in the order the CPU expects them. On x86 and x86-64 that is little-endian: the least significant byte comes first.
import structstruct.pack("<I", 0x080491e2) # b'\xe2\x91\x04\x08' 32-bit, little-endianstruct.pack("<Q", 0x401136) # b'6\x11@\x00\x00\x00\x00\x00' 64-bitstruct.unpack("<I", b"\xe2\x91\x04\x08")[0] == 0x080491e2 # True< is little-endian, > big-endian; I is 4 unsigned bytes and Q is 8. pwntools wraps this as p32() and p64(), but it pays to know what they do underneath.
requests: HTTP without fighting HTTP
Section titled “requests: HTTP without fighting HTTP”requests is the de facto standard library for HTTP. What matters on an engagement:
| You need | How |
|---|---|
| URL parameters | params={"id": 5} |
A form (application/x-www-form-urlencoded) |
data={"user": "a", "pass": "b"} |
| JSON | json={"user": "a"}: it sets the Content-Type for you |
| Headers | headers={"X-Forwarded-For": "127.0.0.1"} |
| Keep cookies across requests | s = requests.Session() and use s.get()/s.post() |
| Don’t follow redirects | allow_redirects=False (to see the 302 and its Location) |
| Self-signed certificate | verify=False |
| Don’t hang forever | timeout=5 on every request |
| See the traffic in Burp | proxies={"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"} |
A Session reuses the connection and stores the cookies the server sends back: it’s what you need to log in and then act as that user.
socket: when it isn’t HTTP
Section titled “socket: when it isn’t HTTP”For services that don’t speak HTTP (FTP, SMTP, a custom service on an odd port), socket opens a TCP connection and lets you send and receive raw bytes. Two details that trip people up at first:
recv(4096)returns up to 4096 bytes, not “the whole message”. If the response is long, you have to read in a loop until nothing else arrives.- Without
settimeout(), arecv()against a service that doesn’t answer waits forever.
subprocess: running commands without opening holes
Section titled “subprocess: running commands without opening holes”subprocess.run() launches a program. The key difference:
| Form | What happens |
|---|---|
run(["nmap", "-sV", ip]) |
nmap runs with exactly those arguments. ip is one argument, even if it contains ;. Careful: argument injection is still possible if the value starts with -; validate the input or use -- before positional arguments when the program supports it. |
run(f"nmap -sV {ip}", shell=True) |
/bin/sh interprets the whole string. If ip is 1.1.1.1; rm -rf ~, both commands run. |
It’s exactly the command injection bug you look for in applications: don’t build it into your own tools.
Concurrency with threads
Section titled “Concurrency with threads”Many engagement tasks are just waiting on the network: trying 1,000 ports, 5,000 paths or 200 passwords. Doing them one after another is slow because most of the time is spent waiting for replies. concurrent.futures.ThreadPoolExecutor runs several at once with a fixed number of threads (max_workers). The limit matters: too many threads will knock over a lab service or trigger a lockout.
Python 2 versus 3 in public exploits
Section titled “Python 2 versus 3 in public exploits”A lot of Exploit-DB code is written in Python 2, which has been unmaintained since 2020. The changes that come up most:
| Python 2 | Python 3 | Note |
|---|---|---|
print "hello" |
print("hello") |
print is a function |
"A" * 100 as a buffer |
b"A" * 100 |
Sockets need bytes |
s.send("USER x\r\n") |
s.send(b"USER x\r\n") |
Same: bytes |
raw_input() |
input() |
|
urllib2.urlopen() |
urllib.request.urlopen() or requests |
|
7 / 2 → 3 |
7 / 2 → 3.5; 7 // 2 → 3 |
Breaks offset and size calculations |
"\x41".encode("hex") |
b"\x41".hex() |
|
except Exception, e: |
except Exception as e: |
In practice
Section titled “In practice”Logging in with a session, through Burp
Section titled “Logging in with a session, through Burp”import requestsimport urllib3urllib3.disable_warnings() # silences the verify=False warning
BURP = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}s = requests.Session()s.proxies = BURPs.verify = False # requests doesn't trust Burp's CA
r = s.post("https://10.10.10.20/login", data={"user": "ana", "pass": "Spring2026"}, allow_redirects=False, timeout=5)print(r.status_code, r.headers.get("Location"))# 302 /panel -> login worked: the server redirects to the panelprint(s.cookies.get_dict())# {'session': 'eyJ1c2VyIjoiYW5hIn0...'} the Session stores the cookie for you
r = s.get("https://10.10.10.20/api/users/2", timeout=5)print(r.status_code, r.json())# 200 {'id': 2, 'user': 'luis', 'email': ...} with ana's cookie you see luis's data: IDOREvery request shows up in Burp’s HTTP history, so you can see exactly what your script sent and replay it in Repeater.
TCP client: banner and conversation
Section titled “TCP client: banner and conversation”import socket
def recv_all(sock, timeout=2): sock.settimeout(timeout) data = b"" try: while True: chunk = sock.recv(4096) if not chunk: # the server closed the connection break data += chunk except socket.timeout: # nothing else is coming pass return data
with socket.create_connection(("10.10.10.20", 21), timeout=5) as s: print(recv_all(s)) # b'220 (vsFTPd 3.0.3)\r\n' banner: service and version s.sendall(b"USER anonymous\r\n") print(recv_all(s)) # b'331 Please specify the password.\r\n' s.sendall(b"PASS x@x.com\r\n") print(recv_all(s)) # b'230 Login successful.\r\n' anonymous FTP allowedMinimal listener
Section titled “Minimal listener”To receive a test connection (for example, to check that a lab machine can reach you):
import socket
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # reuse the port on restartsrv.bind(("0.0.0.0", 9001))srv.listen(1)conn, addr = srv.accept()print("Connection from", addr)# Connection from ('10.10.10.20', 49822)print(conn.recv(1024))conn.close()For interactive shells use nc or the reverse shell tooling: this listener is for understanding the mechanism and for testing.
Threaded port scan
Section titled “Threaded port scan”import socketfrom concurrent.futures import ThreadPoolExecutor
TARGET = "10.10.10.20"
def probe(port): try: with socket.create_connection((TARGET, port), timeout=1): return port except OSError: # closed, filtered or no answer return None
with ThreadPoolExecutor(max_workers=50) as pool: open_ports = [p for p in pool.map(probe, range(1, 1025)) if p]print(open_ports)# [21, 22, 80] 1024 ports in a few seconds instead of minutesIt’s useful for understanding how a scanner works, or on a pivot host where you don’t have nmap. For real work, nmap does this far better.
subprocess done right
Section titled “subprocess done right”import subprocess
r = subprocess.run(["whoami"], capture_output=True, text=True)print(r.returncode, r.stdout.strip())# 0 kalitext=True returns str instead of bytes; a returncode other than 0 means the command failed.
Porting a Python 2 exploit
Section titled “Porting a Python 2 exploit”A typical fragment from an old buffer overflow exploit against a network service:
# Python 2 (original)buf = "A" * 2003 + "\xaf\x11\x50\x62" + "\x90" * 16s.send("TRUN /.:/" + buf)# Python 3 (adapted)import structbuf = b"A" * 2003 + struct.pack("<I", 0x625011af) + b"\x90" * 16s.send(b"TRUN /.:/" + buf)Three things change: everything becomes bytes, the address is written with struct.pack (easier to read and change than hand-reversed bytes) and the command prefix is bytes too.
The ecosystem
Section titled “The ecosystem”| Library | What for | Where it’s used |
|---|---|---|
pwntools |
Binary exploitation and CTFs: connections, packing, assembly, ELF | Binary exploitation |
impacket |
Windows protocols: SMB, Kerberos, LDAP, MSRPC | Impacket |
scapy |
Crafting and dissecting packets by hand | Networking, protocol testing |
paramiko |
SSH client from Python | Automating access with credentials |
requests |
HTTP | Web, APIs |
Next offensive step
Section titled “Next offensive step”- Burp Suite: the natural companion to your web scripts.
- Impacket: Python applied to Active Directory.
- Binary exploitation: where
bytesandstructstop being theory. - Reverse shells: from the test listener to a real shell.
Cheat sheet
Section titled “Cheat sheet”| Concept | What to remember |
|---|---|
str / bytes |
Text / octets. The network and exploits use bytes. |
.encode() / .decode() |
str → bytes / bytes → str. |
struct.pack("<I", x) |
32-bit address, little-endian. |
requests.Session() |
Keeps cookies across requests. |
proxies= + verify=False |
See your scripts in Burp. |
timeout= |
On every request and socket. |
allow_redirects=False |
See the 302 instead of following it. |
recv(n) |
Returns up to n bytes: read in a loop. |
run([...]) |
No shell=True: no command injection (but watch values starting with -). |
ThreadPoolExecutor(max_workers=N) |
Concurrency with a limit. |
7 / 2 in Py3 |
3.5. Use // for integer division. |
| Public exploit | Read, understand, adapt, then run. |
Review questions
Section titled “Review questions”-
Your script does
s.send("USER admin\r\n")and fails withTypeError. Why, and how do you fix it?Answer
In Python 3 sockets only accept bytes and you’re passing a
str. Fix it withs.send(b"USER admin\r\n")ors.send("USER admin\r\n".encode()). -
How do you write the address
0x080491e2into a buffer on x86, and why in that order?Answer
struct.pack("<I", 0x080491e2), which givesb'\xe2\x91\x04\x08'. x86 is little-endian: in memory the least significant byte comes first. -
You log in with
requests.post()and the next request withrequests.get()sends you back to the login page. What’s wrong?Answer
Each standalone call is independent and doesn’t keep the session cookie. Use
requests.Session()and make both requests through that object. -
Why isn’t
recv(4096)enough to read a long response?Answer
Because it returns whatever bytes have arrived so far, at most 4096, not the whole message. You have to read in a loop until the server closes the connection or the timeout fires.
-
What is the security difference between
subprocess.run(["ping", "-c1", host])andsubprocess.run(f"ping -c1 {host}", shell=True)?Answer
In the first,
hostis one argument topingeven if it contains;or|. In the second, the shell interprets the whole string, so ahostlike1.1.1.1; idalso runsid: that’s command injection. -
When porting an exploit,
offset = size / 2gives a different result in Python 3. Why?Answer
In Python 2,
/between integers is integer division; in Python 3 it returns afloat. Use//to keep the original behaviour. -
Why should you cap
max_workersin a threaded scan against a lab machine?Answer
Because too many simultaneous connections can saturate or crash the service, trigger lockouts and give you false negatives from timeouts. A moderate limit is still far faster than going one at a time.