// NotAlive · Python × Cybersecurity · 2026

Python for
Cybersecurity

The complete curriculum. Every keyword, every library, every project — from core Python to writing your first exploit. No fluff. Just the map.

05Stages
30+Topics
13Projects
15+Libraries
// HOW TO USE — Work top to bottom. Each stage builds on the last. Don't skip the projects — reading code doesn't teach you hacking, writing it does. Stages 1–2 move fast if you have CTF experience. Stage 3 is where it gets real.

STAGE 01 Core Language
// the absolute must-knows before touching any library
concepts & keywords
Variables + Data Types
intfloatstrboolbytesbytearraylisttupledictsetNonetype()isinstance()len()
Core containers and primitives. bytes and bytearray are critical — almost all network and binary data is raw bytes. Learn the difference early or it will break you later.
// security use: IPs as strings, ports as ints, raw packets as bytes, scan results in dicts
Loops + Conditionals
forwhileifelifelsebreakcontinuepassrange()enumerate()zip()innot inis
You will loop over wordlists, port ranges, IP lists, and HTTP responses constantly. Know break and continue cold — stopping a scan on first hit matters a lot in practice.
// security use: iterate ports 1–65535, loop through 10M-line wordlists, scan subnets
Functions + Scope
defreturn*args**kwargslambdaglobalnonlocaldefault argstype hintsdocstrings
Every tool should be a collection of focused functions. Avoid monolithic scripts — they're undebuggable at 3am during a CTF. Each function does exactly one thing.
// security use: scan_port(), crack_hash(), send_payload(), parse_response()
String Manipulation
.split().strip().join().replace().find().startswith().endswith().lower()f-strings.format()encode()decode()repr()
Parsing server responses, cleaning log lines, building payloads — all string ops. encode()/decode() bridges str↔bytes which you'll do constantly in network code.
// security use: parse HTTP headers, extract tokens, build SQLi payloads as strings
File I/O
open()read()readline()readlines()write()writelines()with'r' 'w' 'a' 'rb' 'wb'pathlib.Path.exists().read_text()
Wordlists can be 100M lines. Always use with open() and iterate line-by-line — never load the entire file into memory. Use 'rb' for anything binary.
// security use: load rockyou.txt, save scan JSON, read config files, log findings
Error Handling
tryexceptelsefinallyraiseExceptionConnectionRefusedErrorTimeoutErrorsocket.timeoutKeyboardInterruptOSError
A scanner that crashes on the first closed port is useless. Catch specific exceptions, not bare except:. Know your network error types cold.
// security use: handle closed ports, auth failures, resets without stopping the scan
List Comprehensions + Generators
[x for x in y]if filter{k:v for k,v}(x for x)map()filter()sorted()yieldnext()
Generators are memory-efficient for massive datasets. A generator over rockyou.txt uses almost no RAM vs loading all 14 million lines into a list at once.
// security use: filter open ports, transform IP lists, deduplicate findings efficiently
Modules + Imports
importfrom x import yas__name____main__pip installrequirements.txtvenv__init__.py
The if __name__ == "__main__" pattern is non-negotiable. It lets your code work as both a runnable script and an importable module inside a larger recon framework.
// security use: reuse your scanner module inside a bigger framework without rewriting it
build these first
Port Scanner v1
Loop ports 1–1024, attempt TCP connection, print open/closed. Add a timeout so closed ports don't hang. Your first real security tool.
socketfor looptry/exceptfunctions
Wordlist Password Checker
Read a wordlist line-by-line with a generator, check each word against a hash or rule. Works on 100M-line wordlists without crashing your RAM.
file I/Oloopsstringsgenerators
Log Parser
Read an Apache/nginx log, extract IPs and status codes, count hits per IP, flag 404 storms. Pure stdlib — zero dependencies, maximum learning.
file I/Ostring opsdictssorting

STAGE 02 Standard Library
// built-in power — no pip install needed
concepts & keywords
socket
socket.socket()AF_INETSOCK_STREAMSOCK_DGRAM.connect().bind().listen().accept().send().recv().settimeout().close()gethostbyname()
The foundation of all network tools. TCP = SOCK_STREAM (reliable), UDP = SOCK_DGRAM (fast). settimeout() is essential — never let a connect hang forever on a dead host.
// security use: port scanning, banner grabbing, custom TCP listeners, raw connections
re (regex)
re.search()re.match()re.findall()re.finditer()re.sub()re.compile()groups()group(1)\d \w \s \b^ $* + ?re.IGNORECASEre.MULTILINE
Extract structured data from unstructured text. IPs, emails, JWTs, and API keys all follow patterns. Pre-compile with re.compile() in hot loops for speed.
// security use: extract IPs from logs, find API keys in source, parse HTTP headers
subprocess
subprocess.run()Popen()capture_output=Truetext=Trueshell=Truetimeout=.stdout.stderr.returncodeshlex.split()
Wrap external tools (nmap, john, gobuster) and capture their output. Avoid shell=True — use a list of args to prevent shell injection in your own code.
// security use: run nmap and parse output, chain tools in a recon pipeline
hashlib
hashlib.md5()hashlib.sha1()hashlib.sha256()hashlib.sha512().update().hexdigest().digest()pbkdf2_hmac()algorithms_available
Hash functions everywhere in security. MD5/SHA1 are broken but dominate CTFs and legacy systems. Know the difference between a hash, a MAC, and a KDF.
// security use: crack MD5 with wordlist, verify file integrity, understand password storage
argparse
ArgumentParser()add_argument()parse_args()--flag-ftype=intrequired=Truedefault=help=subparsersnargs='+'
Turn scripts into real tools. A proper CLI: --target 10.0.0.1 --ports 1-1024 --threads 50 --output results.json. That's what separates a script from a tool.
// security use: every tool you write needs a proper CLI interface from day one
threading + queue
threading.Thread()target=.start().join()daemon=Truethreading.Lock()with lock:queue.Queue().put().get().task_done()
Single-threaded scanner at 1s timeout over 65535 ports = 18 hours. With 100 threads = 11 minutes. Threading is non-optional for any scanning tool you actually want to run.
// security use: threaded port scanner, parallel hash cracker, concurrent web fuzzer
json + struct
json.loads()json.dumps()json.load()json.dump()indent=sort_keys=struct.pack()struct.unpack()'>I' '<H' 'B' 'Q'
json for API responses and results. struct is critical for binary protocol parsing — reading packet headers, crafting raw payloads, dissecting file formats at byte level.
// security use: parse nmap JSON, unpack TCP headers, read binary file formats
base64 + binascii + codecs
b64encode()b64decode()b32encode()b16encode()binascii.hexlify()binascii.unhexlify().hex()bytes.fromhex()codecs 'rot_13'
Encoding is everywhere in CTFs and real exploits. Base64 in auth headers, hex in shellcode, ROT13 in obfuscation. Encoding ≠ encryption — know this cold.
// security use: decode JWT tokens, encode payloads, convert shellcode between formats
os + sys + pathlib
os.path.join()os.getcwd()os.environos.getenv()os.listdir()os.walk()sys.argvsys.exit()pathlib.Path().glob()
os.walk() is powerful for hunting through directory trees. Combine with regex to find sensitive files: private keys, .env files, database dumps, configs left exposed.
// security use: hunt for .env, id_rsa, *.pem, config.php across a directory tree
urllib + http.server
urllib.parse.urlencode()urllib.parse.quote()urllib.parse.urlparse()http.server.HTTPServerSimpleHTTPRequestHandler
URL encoding is critical for web attacks — & ? = and spaces need encoding in payloads. http.server spins up a file server in one line for payload delivery.
// security use: encode SQLi payloads, serve files for reverse shell delivery in CTFs
build these
Threaded Port Scanner v2
50–100 worker threads, queue of ports, argparse CLI with --target --ports --threads --timeout, JSON output of open ports with service banners.
socketthreadingqueueargparsejson
Banner Grabber
Connect to open ports, grab service banners (SSH version, HTTP server, FTP greeting). Use regex to identify service + version. Save to JSON.
socketrejsonthreading
MD5 Hash Cracker
Take a target hash, iterate a wordlist, hash each word and compare. --algorithm flag for SHA1/SHA256. Show result and time elapsed.
hashlibfile I/Oargparsethreading
Sensitive File Finder
Walk a directory tree searching for .env, id_rsa, *.pem, config.php, *.bak. Report paths and permissions. Pure stdlib, works on Linux and Windows.
os.walkpathlibreargparse

STAGE 03 Third-Party Libraries
// pip install and the ecosystem opens up
web + http
requests
requests.get()requests.post()requests.put()requests.delete()headers={}params={}data={}json={}cookies={}auth=()Session()timeout=verify=False.status_code.text.json().headers.cookies.history
Session() persists cookies across requests — essential for authenticated scanning. verify=False skips SSL cert checks on internal lab targets.
// security use: web fuzzing, form submission, authenticated crawling, API testing
BeautifulSoup (bs4)
BeautifulSoup(html,'html.parser').find().find_all().select().get_text()['href']['action'].attrs.childrenlxml parser
Parse HTML to extract forms, links, hidden fields, comments. Combine with requests to build a web crawler. Find input fields to fuzz for XSS and injection.
// security use: extract forms, find hidden inputs, crawl endpoints, detect HTML comments
httpx + aiohttp
httpx.Client()httpx.AsyncClient()async withawait client.get()aiohttp.ClientSession()asyncio.gather()Semaphorehttp2=True
Async HTTP — send hundreds of requests concurrently without threads. Much faster than requests at scale. Semaphore controls rate to avoid triggering WAFs and IDS.
// security use: async directory brute-forcer, concurrent endpoint fuzzer at real scale
Scapy
IP()TCP()UDP()ICMP()Ether()ARP()DNS()/ (layer stack)send()sr()sr1()sendp()sniff()wrpcap()rdpcap()flags='S'
Build and send raw packets. SYN scans, ARP spoofing, custom DNS, packet sniffing. Understand every byte on the wire. Requires root/admin. Lab machines only.
// security use: SYN scanner, ARP spoofer, DNS amp demo, PCAP analysis
paramiko
SSHClient().connect()AutoAddPolicy().exec_command().open_sftp()Transport()RSAKeyAuthenticationExceptionlook_for_keys=False
SSH in Python. Test auth, run remote commands, transfer files. Catch AuthenticationException for failed logins during credential testing. Lab machines only.
// security use: SSH credential testing, remote command execution (lab only)
impacket
SMBConnection()NTLMAuthNegotiatesecretsdumppsexecGetNPUsersKerberosLDAPDCERPCntlm.compute_response()
Windows network protocol implementation in Python. The backbone of CrackMapExec, BloodHound, and many Windows pen-test tools. Essential for Active Directory work.
// security use: SMB enum, Pass-the-Hash, Kerberoasting, NTLM relay setup
cryptography
Fernet()generate_key().encrypt().decrypt()AESCBC ECB CTR GCMRSAgenerate_private_key()padding.PKCS1v15()OAEP()hashes.SHA256()HMAC()
Proper crypto. AES-ECB is broken (penguins!), use GCM for authenticated encryption. RSA key gen, signing, verification. Used in both attack tooling and defensive code.
// security use: break ECB mode, decrypt captured traffic, forge HMAC, crypto CTFs
pycryptodome
from Crypto.Cipher import AESfrom Crypto.Util import numbergetPrime()inverse()long_to_bytes()bytes_to_long()from Crypto.PublicKey import RSAXOR cipher
CTF crypto staple. number.getPrime() for RSA challenges, long_to_bytes() for BigInteger conversion. Most crypto CTF writeups you'll find are built on this.
// security use: RSA challenges, XOR ciphers, padding oracle, crypto CTF writeups
PyJWT
jwt.encode()jwt.decode()algorithms=['HS256']algorithms=['RS256']verify=Falseoptions={}alg:none attackheader/payload/sig
Decode, forge, and attack JWTs. The alg:none attack, weak secret brute-force, and RS256→HS256 algorithm confusion appear constantly across web targets.
// security use: forge JWT tokens, test weak secrets, exploit algorithm confusion bugs
build these
Directory Brute-Forcer
GET requests to TARGET/word for each wordlist entry. Detect 200/301/302 as hits. Threading, custom headers, --extensions for .php .html .bak
requeststhreadingargparsequeue
SSH Brute-Forcer
Try user:pass pairs from a wordlist against SSH. Catch AuthenticationException for failures, print hits immediately. --delay flag. Lab machines only.
paramikothreadingfile I/Oargparse
ARP Spoofer
Craft ARP replies to poison two hosts' caches, positioning yourself as MITM. Restore real ARP tables on exit via finally block. Root required.
scapyARP()Ether()try/finally
Web Form Fuzzer
Parse all forms with BeautifulSoup. For each input, send a payload list (XSS, SQLi). Flag responses that reflect payloads or error out.
requestsbs4reargparse
JWT Forger
Decode a JWT, modify the payload (role: admin), re-sign with the original secret or test the alg:none bypass. Output the forged token ready to paste.
PyJWTbase64jsonhashlib

STAGE 04 Code Quality
// make tools you can trust, share, and actually run at 3am
concepts & keywords
Classes + OOP
class__init__()self@property@staticmethod@classmethodinheritancesuper()__str__()__repr__()@dataclassABCabstractmethod
Model a Scanner class, a Target class, a Vulnerability class. Makes tools composable. Use @dataclass for clean data containers without boilerplate.
// security use: Scanner(target, ports, threads) — a clean API for complex tools
logging
logging.getLogger()basicConfig()DEBUG INFO WARNING ERROR CRITICAL.debug().info().warning().error()FileHandler()StreamHandler()Formatter()
Replace every print() with proper logging. Set level via CLI: --verbose → DEBUG, default → INFO. Log to file and console simultaneously for a clean audit trail.
// security use: audit trail of every action your tool takes — required for legal pen testing
Type Hints + mypy
def f(x: int) -> strList[str]Dict[str, Any]Optional[str]Union[int, str]Tuple[int, ...]Callablefrom typing importmypy
Type hints make function signatures self-documenting and catch bugs before runtime. A bytes/str mismatch in an exploit script can be catastrophic — catch it statically first.
// security use: prevent silent type bugs that would break exploits at the worst moment
Testing (pytest)
pytestdef test_*()assert@pytest.fixture@pytest.mark.parametrizemonkeypatchtmp_pathunittest.mockMagicMock()patch()
Test scanner logic without hitting real hosts. Mock network calls with unittest.mock. Parametrize to cover edge cases: closed ports, timeouts, auth failures.
// security use: verify tool logic before running it against a real live target
Configuration
configparsertomllibpython-dotenvload_dotenv()os.getenv()pydanticBaseSettingsyaml
Never hardcode API keys, IPs, or credentials. Use .env files via python-dotenv. Pydantic BaseSettings validates config and gives type-safe access with sane defaults.
// security use: keep API keys and target configs out of your source code entirely
Packaging + Distribution
pyproject.tomlsetup.pyrequirements.txtpip freezevenvpipenvpoetryentry_points__version__Makefile
Share tools properly. requirements.txt + README.md is minimum. A pyproject.toml lets others pip install your tool directly from GitHub.
// security use: publish tools on GitHub as a portfolio — every recruiter will look
build these
Recon Framework v1
Combine port scanner, banner grabber, and web fuzzer into one modular framework. Clean class architecture: Target, Scanner, Reporter. JSON + HTML output. Logging and CLI.
OOPloggingargparsejsonthreading
Vuln Report Generator
Take JSON scan results, classify by severity, generate a structured HTML report with CVE references and remediation advice. Jinja2 for templating.
jsonjinja2dataclassespytest

STAGE 05 Advanced — Exploit Dev + Specialist
// where your CTF experience pays off hardest
binary exploitation
pwntools
process()remote()gdb.attach().send().sendline().recv().recvuntil().recvline()p32() p64()u32() u64()flat()cyclic()cyclic_find()ROP().chain()ELF()context.archasm()shellcraft
The CTF exploit framework. cyclic() finds buffer overflow offsets. ROP() builds ROP chains. ELF() parses binaries. You've probably touched this already in CTFs.
// security use: buffer overflows, ROP chains, format strings, shellcode injection
struct + ctypes
struct.pack(fmt,*v)struct.unpack()< > ! (endianness)B H I Q (sizes)ctypes.cdll.LoadLibrary()ctypes.windllctypes.cast()c_char_pc_void_pcreate_string_buffer()
struct packs/unpacks binary data for protocol parsing. ctypes calls native C/Windows API functions directly — used in shellcode loaders and DLL injection scripts.
// security use: binary protocols, Windows shellcode loaders, call VirtualAlloc/CreateThread
angr + z3
angr.Project()claripyBVS() BVV()state.solverSimulationManager().explore()find= avoid=z3.Solver()z3.Int()z3.BitVec().add().check().model()
Symbolic execution and constraint solving — find inputs that reach a target code path automatically. z3 solves constraint puzzles in hard CTF challenges without any manual reversing.
// security use: auto-solve crackmes, find license keys, break obfuscated checks
async + performance + specialist
asyncio
async defawaitasyncio.run()asyncio.gather()asyncio.create_task()asyncio.Semaphore()asyncio.Queue()asyncio.open_connection()asyncio.wait_for()event loopcoroutine
True concurrency for I/O-bound tasks. An async port scanner handles 10,000 concurrent connections. Semaphore throttles rate to avoid triggering IDS or rate limits.
// security use: massively fast port scanner, concurrent web crawler, async brute-forcer
multiprocessing
Process()Pool().map().starmap()Queue()Pipe()Manager()Value()cpu_count()Pool(os.cpu_count())
For CPU-bound tasks like hashing. Threading is limited by the GIL for CPU work — multiprocessing uses all cores in parallel. Use for hash cracking at real scale.
// security use: parallel hash cracking, CPU-intensive crypto attacks across all cores
pefile + lief
pefile.PE().sections.imports.exports.OPTIONAL_HEADERlief.parse().add_section().patch_address()ELF MachO PE
Parse and modify PE (Windows EXE/DLL) and ELF (Linux) binaries. Read import tables to identify malware capabilities. Patch binaries, add sections, inject code. Static analysis staple.
// security use: malware static analysis, binary patching, packer identification
frida (Python bindings)
frida.attach()frida.spawn()session.create_script()script.exportsInterceptor.attach()Memory.read*()Memory.write*()NativeFunction()ObjC.classes
Dynamic instrumentation — hook into running processes, modify return values, dump memory, bypass SSL pinning in mobile apps. Python drives the Frida agent from outside the process.
// security use: bypass SSL pinning, hook crypto functions, dynamic malware analysis
build these
Buffer Overflow Exploit
pwntools exploit for a vulnerable 32-bit ELF. Find offset with cyclic(), control EIP, redirect to shellcode or ret2libc. Against your own compiled binary.
pwntoolsELF()cyclic()ROP()asm()
Async Subnet Scanner
Scan a /24 — all 254 hosts, top 1000 ports — in under 60 seconds. asyncio + Semaphore(500). Output live hosts and open ports as JSON in real-time.
asyncioopen_connectionSemaphorejson
Crackme Solver (angr)
Point angr at a crackme binary. Define "success" as find= and "fail" as avoid=. Symbolic execution finds the valid input automatically. No manual reversing needed.
angrclaripySimulationManager
PE Static Analyzer
Take a suspicious EXE, extract imports, section entropy (high = packed), strings, compile timestamp. Flag suspicious patterns. Output a JSON report.
pefilemath (entropy)rejson

Full Keyword Tree

// every import and concept flattened into one view

Python × Cybersecurity
├──Stage 1 · Core Language
├──Data types
intfloatstrboolbytesbytearraylisttupledictsetNone
├──Control flow
forwhileif/elif/elsebreakcontinuepassrange()enumerate()
├──Functions
defreturn*args**kwargslambdatype hintsdocstrings
├──Strings
f-strings.split().strip().join().replace()encode()decode()
├──File I/O
open()withread()write()'rb' 'wb'pathlib.Path
└──Error handling
try/except/finallyraiseConnectionRefusedErrorTimeoutError
├──Stage 2 · Standard Library
├──socket
AF_INETSOCK_STREAMSOCK_DGRAM.connect().recv().settimeout()gethostbyname()
├──re
search()findall()sub()compile()groups()IGNORECASEMULTILINE
├──subprocess
run()Popen()capture_output.stdout.returncodeshlex.split()
├──hashlib
md5()sha1()sha256().hexdigest()pbkdf2_hmac()
├──threading
Thread().start().join()Lock()queue.Queue()daemon=True
├──argparse
ArgumentParser()add_argument()parse_args()type=required=
├──base64 + binascii
b64encode()b64decode()hexlify()unhexlify().hex()fromhex()
└──json + struct
loads()dumps()pack()unpack()'<I' '>H' 'B'
├──Stage 3 · Third-Party Libraries
├──requests
get() post()Session()headers=cookies=.status_code.text.json()
├──BeautifulSoup
BeautifulSoup()find()find_all()select()['href'].get_text()
├──Scapy
IP() TCP() UDP() ICMP() ARP() Ether()send() sr() sr1() sniff()
├──paramiko
SSHClient().connect()exec_command()AuthenticationException
├──cryptography
Fernet()AES CBC GCM ECBRSAHMAC()padding.PKCS1v15()
├──pycryptodome
AESgetPrime()long_to_bytes()inverse()XOR
├──PyJWT
encode()decode()algorithms=alg:noneverify=False
└──impacket
SMBConnectionNTLMKerberossecretsdumpDCERPC
├──Stage 4 · Code Quality
├──OOP
class__init__@property@dataclasssuper()ABC
├──logging
getLogger()DEBUG/INFO/WARNING/ERRORFileHandlerFormatter
├──type hints
x: int-> strOptional[]List[]Dict[]mypy
├──pytest
def test_*()assertfixtureparametrizemock.patch()
└──packaging
pyproject.tomlrequirements.txtvenvpoetryentry_points
└──Stage 5 · Advanced
├──pwntools
process() remote()p32() p64() u32() u64()cyclic()ROP()ELF()asm()shellcraft
├──ctypes
cdll.LoadLibrary()windllc_char_pc_void_pcreate_string_buffer()
├──asyncio
async defawaitgather()Semaphore()open_connection()wait_for()
├──angr + z3
Project()SimulationManager()find= avoid=z3.Solver()BVS() BVV()
├──pefile + lief
PE().sections.importslief.parse().patch_address()
└──frida
attach()spawn()create_script()Interceptor.attach()Memory.read*()
email:   admin@notalive.in
discord: _i_am_innocent_
github:  github.com/notalive24