GHOSTNET›MOD-15 // PYTHON & BASH FOR SECURITY
ALL MODULES →
MODULE 15 · SCRIPTING

PYTHON & BASH FOR SECURITY

Automation mindset · Bash · grep / awk / jq · Python · Sockets & APIs · Parsing & IOCs · cron & alerting · PowerShell · Shipping tools

9
CHAPTERS
~3hr
TOTAL READ
BEGINNER
DIFFICULTY
MOD-15
IDENTIFIER
BEGINNER~15 min READCHAPTER 1 OF 9

Why Defenders and Attackers Script

KEY POINTS · THE QUICK VERSION
  • Scripting turns a task you do by hand into a repeatable, reviewable, testable procedure - the same skill powers SOC triage, incident response, red team tooling and bug bounty recon.
  • Bash is the glue for Linux and its text tools, Python is the general-purpose language for parsing, networking and APIs, PowerShell is the native object-based shell of Windows and Active Directory.
  • A useful rule: if you do it three times, script it; if a mistake would hurt, add a dry-run mode and a scope check first.
  • Attackers script to scale and to live off the land; defenders script to triage faster, enrich alerts and catch exactly those living-off-the-land techniques.
  • Never run code you do not understand - including code from forums, gists or AI assistants. Read it, run it in a lab, then promote it.
Scan these first, then read below for the depth and examples — or jump straight to the lab.
◈ PICTURE IT — MTAANI EDITION

Scripting is hiring a tireless mkokoteni boy who never sleeps and never forgets. Anything you find yourself doing by hand more than twice — renaming 200 files, checking which servers are up, pulling the same numbers every morning — you write down once, and he repeats it perfectly at 3am while you rest. A script is just those instructions, written clearly enough that the machine can follow them without you standing over it.

► The Automation Mindset

Picture a night-shift analyst. At 02:00 an alert fires: a web server is seeing thousands of failed SSH logins. Without scripting, the analyst opens the log in a text editor, scrolls, copies IP addresses into a spreadsheet, looks each one up in a threat-intel site, and writes a ticket. That takes an hour and is full of copy-paste mistakes. With a ten-line script, the same work takes four seconds, produces the same answer every time, and can run again tomorrow without anyone awake. That is the whole argument for this module.

Scripting is not a separate career path from security - it is a force multiplier inside every path. A penetration tester scripts recon so every engagement starts the same way. A SOC analyst scripts enrichment so alerts arrive with context already attached. An incident responder scripts evidence collection so it is consistent and defensible in court. A threat hunter scripts queries across thousands of endpoints. Even a GRC analyst scripts the boring evidence pulls for an audit. You do not need to become a software engineer. You need to become dangerous with a terminal and a text editor.

The mindset has four parts. First, notice repetition: any task you have done three times by hand is a candidate. Second, make it reproducible: the script is documentation that actually runs - a colleague can read exactly what you did. Third, make it safe: scripts act fast, so mistakes also happen fast. Build in dry-run modes, confirmations and scope checks. Fourth, make it observable: log what the script did, so when it fails at 03:00 you know why.

► How Attackers Use Scripts

Attackers script for scale and stealth. A single operator with a Python script can test leaked credentials against hundreds of login portals, parse the results and pivot to the ones that worked. Ransomware affiliates use PowerShell and batch scripts to disable backups, push payloads with remote management tools and wipe logs. Most importantly, attackers love built-in interpreters - Bash on Linux, PowerShell on Windows - because they are already installed, trusted and signed. This is called living off the land: no custom malware binary to detect, just a legitimate interpreter running hostile instructions.

This is exactly why defenders must read scripts fluently. When you pull a suspicious command line out of an EDR alert, it will often be a one-liner: a base64-encoded PowerShell command, a curl piped into sh, a Python reverse shell. If you cannot read it, you cannot judge it. Chapter 8 teaches you to decode an encoded PowerShell command with three lines of Python.

► How Defenders Use Scripts

TaskManual timeScripted timeTypical tools
Count failed SSH logins per IP30-60 minSecondsgrep, awk, sort, uniq
Enrich 200 IOCs with threat intelHoursMinutes (rate-limited)Python + requests + an intel API
Find new open ports since last weekHours of comparisonSecondsnmap -oX + Python XML diff
Pull failed Windows logons from 50 hostsA day of RDP sessionsMinutesPowerShell Get-WinEvent + remoting
Extract IOCs from a threat report PDF/text45 minSecondsPython regex + ipaddress validation
Hash every file in a suspicious folder20 minSecondssha256sum, Python hashlib

► Choosing the Right Language

There is no single best language. Experienced practitioners switch between three depending on the job, and often combine them - a Bash wrapper that calls a Python parser, or a Python script that shells out to a PowerShell command on a Windows host.

LanguageBest atWeak atWhere it already exists
BashGluing command-line tools, quick text pipelines, server admin, cron jobsComplex data structures, error handling, anything over ~150 linesEvery Linux distro, macOS (zsh default, bash available), WSL
PythonParsing, networking, APIs, data analysis, real tools with testsStartup time for tiny tasks, dependency management if carelessMost Linux distros, Kali, macOS (via Xcode tools or Homebrew); installable on Windows
PowerShellWindows administration, AD, event logs, Microsoft 365 and AzureUnix text tools, portability to minimal Linux boxesEvery modern Windows (5.1 built in); PowerShell 7 is cross-platform
DECISION SHORTCUT
Is it a one-off pipeline over text files on Linux?        -> Bash one-liner
Will it grow past a page, need JSON/HTTP, or need tests?  -> Python
Is the data inside Windows (event logs, AD, registry)?    -> PowerShell
Will someone else run it on a schedule?                   -> Python or PowerShell,
                                                             with logging and --help

► The Same Task in Three Languages

To see the personalities, here is one task - count lines containing the word Failed in a log file - written three ways. Notice that Bash leans on an existing tool, Python reads the file explicitly, and PowerShell passes objects down a pipeline.

BASH
grep -c "Failed" auth.log
PYTHON
count = 0
with open("auth.log", encoding="utf-8", errors="replace") as f:
    for line in f:
        if "Failed" in line:
            count += 1
print(count)
POWERSHELL
(Select-String -Path ./auth.log -Pattern "Failed").Count

The Bash version is shortest because grep already exists and is fast. The Python version is longer but every step is explicit, and it is easy to extend: tomorrow you might want to extract the IP, group by hour and send a JSON report to a webhook. That kind of growth is where Python wins.

► Safety Principles From Day One

Scripts amplify intent. A typo in a manual command breaks one thing; a typo in a loop breaks everything the loop touches. Build these habits before you write anything clever:

PrincipleWhat it looks like in practice
Scope firstTargets come from an allow-list file you control; the script refuses anything outside it.
Dry runA --dry-run flag prints what would happen without doing it. Make it the default for destructive actions.
Fail loudlyBash: set -euo pipefail. Python: let unexpected exceptions crash with a traceback instead of hiding them.
Least privilegeDo not run as root or Administrator unless the step genuinely needs it.
No secrets in codeAPI keys come from environment variables or a secrets manager, never from the script or git.
Log what you didTimestamped logs to a file or stderr, so the 03:00 failure can be explained at 09:00.
WARNING
AI coding assistants can produce working scripts in seconds, and they are genuinely useful. They also confidently produce scripts that delete the wrong directory, scan the wrong subnet or invent library functions that do not exist. Treat generated code exactly like code from a stranger on a forum: read every line, run it in a lab, and only then point it at anything real.

► Setting Up Your Workbench

You need a Linux shell, Python 3 and optionally PowerShell. Kali, Ubuntu, Debian and Fedora all ship Bash and Python 3. On Windows, install WSL (wsl --install from an administrator terminal) to get a real Linux environment alongside native PowerShell. On macOS the default shell is zsh, which runs almost all of the Bash in this module, but you can run bash explicitly. Install shellcheck (a Bash linter) and a code editor with Python support. Every example in this module targets lab files, documentation IP ranges (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, reserved by RFC 5737 for examples) or localhost - never real third-party systems.

CHECK YOUR TOOLS
$ bash --version | head -1
GNU bash, version 5.2.37(1)-release (x86_64-pc-linux-gnu)
$ python3 --version
Python 3.13.5
$ pwsh --version          # optional, PowerShell 7 on Linux/macOS
PowerShell 7.5.2
$ sudo apt install shellcheck jq    # Debian/Ubuntu/Kali

Version numbers on your machine will differ; anything from Bash 5, Python 3.10 and PowerShell 7.4 upward works for this module. With the workbench ready, Chapter 2 starts with the shell you already have open.

RECAP · CHECK YOURSELF
  • Scripting turns a task you do by hand into a repeatable, reviewable, testable procedure - the same skill powers SOC triage, incident response, red team tooling and bug bounty recon.
  • Bash is the glue for Linux and its text tools, Python is the general-purpose language for parsing, networking and APIs, PowerShell is the native object-based shell of Windows and Active Directory.
  • A useful rule: if you do it three times, script it; if a mistake would hurt, add a dry-run mode and a scope check first.
  • Attackers script to scale and to live off the land; defenders script to triage faster, enrich alerts and catch exactly those living-off-the-land techniques.
  • Never run code you do not understand - including code from forums, gists or AI assistants. Read it, run it in a lab, then promote it.
Read to the end to count this chapter
▸ READY TO PRACTISE
You've now covered enough for Lab steps 1–2 of 18. Try them in the lab while it's fresh.
OPEN LAB ▸
⚡ TEST YOURSELF
End-of-chapter quiz
A dozen questions — recall and practical. Graded, earns up to 20 XP.
PRACTISE IN THE LAB ▸
READY TO PRACTICE?
MOD-15 Interactive Lab: Automate the Night Shift
18 steps · 360 XP · Real commands · Flag captures
LAUNCH LAB →
ALL MODULES →