Skip to content

Python for Hacking

Python is the default language of offensive security: most tools (impacket, sqlmap, scapy, many exploits) are written in it, and when a tool doesn’t do exactly what you need, a Python script solves it. HTTP requests, sockets, parsing, exploit automation, PoCs: it all fits in a few lines. It’s the backbone of the Offensive Python course.

# variables and types
host = "10.0.0.1"; port = 445; active = True
lst = [22, 80, 443]; d = {"user": "admin", "pass": "x"}
# control flow
for p in lst:
if p == 443: print("https")
while active: break
# functions
def scan(host, port):
return f"{host}:{port}"
import requests
r = requests.get("https://target/api", params={"id": 1},
headers={"User-Agent": "x"}, timeout=5, verify=False)
print(r.status_code, len(r.text))
r = requests.post("https://target/login", data={"u":"a","p":"b"},
cookies={"session":"..."})
# follow redirects, persistent sessions:
s = requests.Session(); s.get(...)

With this you automate fuzzing, login brute force, IDOR by ID, etc.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
if s.connect_ex(("10.0.0.1", 22)) == 0: # 0 = open
print("22 open")
print(s.recv(1024)) # banner grabbing
s.close()

Basis of a homemade port scanner and of interacting with raw TCP services.

# read a wordlist / target list
with open("users.txt") as f:
users = [l.strip() for l in f]
# regex to extract data (see fund-regex)
import re
emails = re.findall(r"[\w.]+@[\w.]+", text)
# command-line arguments
import argparse
p = argparse.ArgumentParser(); p.add_argument("--host"); args = p.parse_args()
requests / httpx # HTTP
scapy # craft/manipulate packets at a low level
impacket # Windows/AD protocols (SMB, Kerberos, MSRPC)
pwntools # binary exploitation / CTF
beautifulsoup4 # parse HTML (scraping)
paramiko # SSH
python3 -m venv venv && source venv/bin/activate # isolated environment
pip install requests # dependencies

Use a venv per project so you don’t break dependencies; use -I when running scripts that read untrusted files.

When the public exploit doesn’t fit, you adapt it in Python. When you need to repeat an attack with logic (conditions, state, response parsing), Bash falls short and Python shines. And to read/understand offensive tools —almost all in Python— you must know Python.

  • I handle types, lists, dicts, loops, and functions
  • I make GET/POST requests with requests and handle sessions/cookies
  • I open TCP sockets to scan ports or banner-grab
  • I read files (wordlists) and extract data with regex
  • I parse arguments with argparse
  • I know requests, scapy, impacket, pwntools and what they’re for
  • I use venv and understand why to isolate dependencies