01. Intro to Python
Overview¶
Python is one of the most widely used programming languages in cybersecurity. Its simplicity, flexibility, and large collection of libraries make it ideal for automation, scripting, penetration testing, malware analysis, and digital forensics.
This guide introduces Python basics tailored for cybersecurity learners.
Why Python for Cybersecurity?¶
-
Easy to learn and write scripts quickly
-
Cross-platform (works on Linux, Windows, Mac)
-
Huge number of security-focused libraries (Scapy, Nmap, Requests, etc.)
-
Great for automation, data parsing, and network tasks
-
Widely used in pentesting, SOC automation, and threat hunting
Python Basics You Should Know¶
1. Printing and Variables¶
print("Hello, Cybersecurity World!")
# 01. Intro to Python
ip = "192.168.1.1"
port = 22
print(f"Target IP: {ip}, Port: {port}")
2. Data Types¶
-
Strings:
"admin","password123" -
Integers:
80,443 -
Lists:
["192.168.1.1", "192.168.1.2"] -
Dictionaries:
{"username": "admin", "password": "1234"}
3. Control Flow¶
4. Loops¶
5. Functions¶
Python in Cybersecurity¶
1. Working with Files¶
2. Networking with socket¶
import socket
ip = "127.0.0.1"
port = 80
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, port))
if result == 0:
print("Port is open")
else:
print("Port is closed")
sock.close()
3. Web Requests¶
import requests
url = "http://example.com"
response = requests.get(url)
print("Status Code:", response.status_code)
4. Using External Tools (subprocess)¶
Useful Libraries for Security¶
-
socket→ Networking & scanning -
requests→ HTTP requests & web testing -
scapy→ Packet crafting/sniffing -
subprocess→ Run system tools (Nmap, Netcat, etc.) -
os&sys→ System interaction -
cryptography→ Encryption & hashing
Learning Roadmap (Beginner → Advanced → Project ideas)¶
Stage 0 — Setup (0–2 days)¶
-
Install Python 3.x, set up
venv -
Familiarize with terminal (Linux preferred)
-
Install
pip,requests,scapy,cryptography,paramiko,beautifulsoup4
Stage 1 — Fundamentals (1–2 weeks)¶
-
Variables, types, control flow, functions, modules
-
File I/O, exception handling, regular expressions (
re) -
Small scripts: file parser, simple network probe (sockets)
-
Goal: Build a CLI script that reads a list of IPs and prints reachable hosts
Stage 2 — Networking & Automation (2–4 weeks)¶
-
Sockets deeper (TCP/UDP basics)
-
subprocessto callnmap,tcpdump, parse outputs -
Learn
scapybasics: send/receive packets, craft simple packets -
Automate SSH tasks with
paramiko -
Goal: Create an automated reconnaissance script that runs nmap + grabs HTTP titles
Stage 3 — Web & Parsing (2–3 weeks)¶
-
requests+ session handling, cookies, headers -
BeautifulSoup/lxmlfor scraping and parsing -
Basic vulnerability checks: detect default pages, common misconfigs
-
Goal: Build a scanner that finds exposed admin pages and reports status codes
Stage 4 — Cryptography & Forensics (2–4 weeks)¶
-
Hashing (
hashlib), symmetric/asymmetric basics (cryptography) -
File hashing, verifying integrity, simple encrypt/decrypt scripts
-
Basic log forensics: timeline generation, parsing structured logs (JSON)
-
Goal: Create a hash-based duplicate detector and an encrypted vault for notes
Stage 5 — Detection & ML Basics (optional, 3–6 weeks)¶
-
Parse logs to extract features (IP frequency, failed auth spikes)
-
Use
scikit-learnto build a simple anomaly detector (e.g., clustering or isolation forest) -
Goal: Prototype a script that flags suspicious IPs based on login behavior
Stage 6 — Tooling & Packaging (ongoing)¶
-
Add CLI arguments (
argparse) and config files (yaml/json) -
Logging (
loggingmodule), structured output (JSON) -
Create small modules and package with
setup.cfgorpyproject.toml -
Add unit tests (
pytest) and basic CI (GitHub Actions)
Practical Projects (pick 2–3)¶
-
Port Scanner — multi-threaded scanner that writes CSV/HTML report.
-
Simple IDS Log Parser — parse logs and alert on rules (regex-based).
-
HTTP Recon Tool — enumerate endpoints, capture response headers, look for sensitive info.
-
SSH Automation Suite — run checks across hosts via SSH and collect outputs.
-
Phishing URL Classifier (basic ML) — label dataset, extract features, train a classifier. (Educational only)
Project Templates (mini examples)¶
Port scanner (single-thread)
import socket, sys
def is_open(host, port, timeout=1):
s = socket.socket()
s.settimeout(timeout)
try:
s.connect((host, port))
s.close()
return True
except:
return False
print(is_open("127.0.0.1", 22))
Log parser (count failed logins)
from collections import Counter
with open("auth.log") as f:
ips = [line.split()[-1] for line in f if "Failed password" in line]
print(Counter(ips).most_common(10))
Learning Checklist (tick off as you go)¶
-
Python basics (variables, loops, functions)
-
File I/O & regex
-
socket& simple networking scripts -
requests& web scraping basics -
scapybasics (packet crafting/sniffing) -
Automating command-line tools (
subprocess) -
Basic cryptography and hashing
-
Learn to automate reconnaissance (whois, nslookup, subdomain scans)
-
Build a simple port scanner
-
Write scripts for brute force (educational & legal use only!)
-
Automate log parsing for security monitoring
-
Explore libraries like Scapy, Paramiko, PyCrypto, BeautifulSoup