Home
Cybersecurity & AI Security / Part 6 — Programming for Security: Python & Scripting Basics

Programming for Security: Python & Scripting Basics

CAP, ACID vs BASE, latency numbers, back-of-envelope estimation, single points of failure — the vocabulary every system designer thinks in.


Core Philosophy: Pre-built tools handle the common 80% of security work. The remaining 20% — the custom, the unusual, the specific-to-this-target — is where real skill shows, and it needs scripting. You don’t need to be a software engineer. You need to read other people’s exploit code without fear, and write small scripts that automate the tedious. Since you already code, this section is about aiming that ability at security.

Part 1: The Problem

Throughout this curriculum you’ll hit moments no tool fits perfectly:

Each of these is a few lines of Python. A security practitioner who can’t script is permanently limited to what others have already built. You already program — this section points that skill at security and shows the few patterns that come up again and again.

Part 2: Why Python Specifically

You could script in many languages. Security overwhelmingly uses Python, for concrete reasons:

You’ll also meet Bash (Part 6) for gluing command-line tools together. Python for logic; Bash for chaining tools. That pairing covers almost everything.

Part 3: The Building Blocks You’ll Actually Use

Since you already code, this is a mapping exercise — the same constructs you know, in their security-scripting form. The recurring four:

1. Variables and strings — security scripting is mostly manipulating text: URLs, payloads, responses, tokens.

2. Loops — the workhorse. “Try every password in this list.” “Check every port from 1 to 1000.” “Test every URL in this file.”

python
passwords = ["123456", "password", "admin", "letmein"]
for pw in passwords:
    print(f"Trying password:{pw}")
    # (here you would actually test it against a LEGAL target)

3. Conditionals — reacting to results. “If the response says ‘Welcome’, the login worked.”

python
if "Welcome" in response_text:
    print("[+] Login succeeded")
else:
    print("[-] Login failed")

4. Functions — packaging a repeated action so you write it once and reuse it.

python
def check_port(host, port):
    # returns True if the port is open, False otherwise
    ...

If those four feel familiar from your existing coding, you already have what you need. Security scripting is ordinary programming pointed at security problems.

Part 4: The Two Libraries to Know First

Python’s power for security is in its libraries. Two come up immediately.

requests — for talking to web servers. This library sends the HTTP requests from section 0.3, in code. It is the foundation of nearly all web-app scripting.

python
import requests

# Send a GET request to a target (use a LEGAL target — your lab,
# or a site that explicitly permits automated testing)
response = requests.get("http://your-lab-target/login")

print(response.status_code)   # e.g. 200
print(response.headers)       # the response headers
print(response.text[:200])    # first 200 chars of the body

With requests you can automate logins, submit forms, fuzz inputs, and crawl pages — programmatically doing what section 0.3 did by hand.

socket — for raw network connections. Lower-level: it opens direct TCP connections to a host and port. It’s how you’d build a port scanner from scratch — and building one teaches you what Nmap does under the hood.

Part 5: Reading Exploit Code Without Fear

A skill as important as writing scripts is reading them. You’ll constantly find public exploit code and proof-of-concept scripts. Two rules:

1. Never run a script you don’t understand — especially with sudo. Public exploit code can be wrong, outdated, or deliberately malicious (some “exploits” actually attack the person who runs them). Always read it first. Ask: what does it connect to? what does it send? does it download or execute anything? does it touch files outside the target?

2. Read it in the order the computer does. Find where execution starts (often the bottom, or a main()), then follow the flow. You’re not memorizing it — you’re answering “what will this do, and is it safe and appropriate to run here?”

This habit protects you and sharpens you: every exploit you read teaches you a technique.

Part 6: A Word on Bash Scripting

Bash is the Linux shell’s own scripting language. Where Python gives you logic and libraries, Bash excels at gluing command-line tools together and automating sequences of terminal commands.

bash
#!/bin/bash
# Run three scans in a row and save each to a file
nmap -sV target > scan_services.txt
nmap -p- target > scan_allports.txt
echo "Scans complete."

You don’t need deep Bash now. Just recognize it, and know the division of labor: Python for logic and data, Bash for chaining tools. Together they cover the scripting needs of this whole curriculum.

📓 Key Terms

Term Plain meaning
ScriptA short program for automating a task.
PythonThe dominant scripting language in security.
Library / moduleReusable code you import (e.g. requests, socket).
requestsPython library for sending HTTP requests in code.
socketPython module for raw TCP/network connections.
Exploit code / PoCA script that demonstrates or performs an attack.
BashThe Linux shell’s scripting language; glues tools together.

🧪 Hands-On Lab

Run these in your Kali VM (Python and these libraries are already there).

Task 1 — Confirm your tools.

text
python3 --version
python3 -c "import requests; print('requests OK')"

If requests is missing on a non-Kali system: pip3 install requests.

Task 2 — A simple HTTP request script. Create fetch.py:

python
import requests

# Use a legal target: your own lab VM, or a site that explicitly
# permits automated requests.
url = "http://localhost"
response = requests.get(url)

print(f"Status code:{response.status_code}")
print(f"Server header:{response.headers.get('Server')}")
print(f"First 100 chars of body:\n{response.text[:100]}")

Run python3 fetch.py. You just did section 0.3’s request/response in code.

Task 3 — A tiny port scanner. Create scanner.py:

python
import socket

target = "127.0.0.1"          # your own machine — legal to scan
ports_to_check = [22, 80, 443, 3306, 8080]

for port in ports_to_check:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1)
    result = sock.connect_ex((target, port))   # 0 means the port is open
    if result == 0:
        print(f"[+] Port{port} is OPEN")
    else:
        print(f"[-] Port{port} is closed")
    sock.close()

Run python3 scanner.py. You built a miniature Nmap. Compare its results to nmap localhost from section 0.4 — same idea, and now you know what’s happening inside the tool.

Task 4 — Read someone else’s code. Find any small, well-known open-source security script online. Don’t run it. Just read it top to bottom and answer: What does it connect to? What does it send? Would it be safe and appropriate to run against a target I own? This is a skill you’ll use for years — practice it deliberately.

Task 5 — Extend the scanner (stretch). Modify scanner.py to scan a range of ports (e.g. 1–1024) using a loop, and to print a final count of how many were open.

⚠️ Common Mistakes

✅ Recap & What’s Next

Phase 0 complete. You can now picture how data moves, operate a Linux terminal, read the web’s HTTP language, think in terms of attack surface, run a safe legal lab, and script the gaps. That is the entire foundation.

Next — Phase 1: Security Fundamentals & the Attacker Mindset. It opens with the most important page in the curriculum: 1.0 — Rules of Engagement, the law and ethics that separate a security professional from a criminal. Read it before you attack anything.

📋 Phase 0 — Page Checklist

Use this as a Notion to-do list. Tick each page as you finish its reading and its hands-on lab.

Two living pages to start now and grow through the whole curriculum:

⁂ Back to all modules