New to Python? That's fine. This workbook teaches Python through security projects. Each chapter builds something real. Type the code yourself โ don't paste. Muscle memory matters.
Chapter 1 โ Why Python?
Python is the scripting language of security. Here's why:
- Kali Linux ships with Python 3 pre-installed
- All major security tools have Python bindings (nmap, scapy, impacket)
- Quick to write โ build a port scanner in 10 lines
- Rich libraries:
socket,requests,subprocess,scapy,paramiko(SSH) - CTF challenges often require a quick Python script to solve
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 in
Chapter 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 fundamentals
Workbook Complete! Python unlocks the ability to automate everything in security. Build your own tools โ it teaches you more than using pre-made ones. Every tool you write is something you fully understand.