PYTHON & BASH FOR SECURITY
Automation mindset · Bash · grep / awk / jq · Python · Sockets & APIs · Parsing & IOCs · cron & alerting · PowerShell · Shipping tools
Why Defenders and Attackers Script
- 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.
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
| Task | Manual time | Scripted time | Typical tools |
|---|---|---|---|
| Count failed SSH logins per IP | 30-60 min | Seconds | grep, awk, sort, uniq |
| Enrich 200 IOCs with threat intel | Hours | Minutes (rate-limited) | Python + requests + an intel API |
| Find new open ports since last week | Hours of comparison | Seconds | nmap -oX + Python XML diff |
| Pull failed Windows logons from 50 hosts | A day of RDP sessions | Minutes | PowerShell Get-WinEvent + remoting |
| Extract IOCs from a threat report PDF/text | 45 min | Seconds | Python regex + ipaddress validation |
| Hash every file in a suspicious folder | 20 min | Seconds | sha256sum, 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.
| Language | Best at | Weak at | Where it already exists |
|---|---|---|---|
| Bash | Gluing command-line tools, quick text pipelines, server admin, cron jobs | Complex data structures, error handling, anything over ~150 lines | Every Linux distro, macOS (zsh default, bash available), WSL |
| Python | Parsing, networking, APIs, data analysis, real tools with tests | Startup time for tiny tasks, dependency management if careless | Most Linux distros, Kali, macOS (via Xcode tools or Homebrew); installable on Windows |
| PowerShell | Windows administration, AD, event logs, Microsoft 365 and Azure | Unix text tools, portability to minimal Linux boxes | Every modern Windows (5.1 built in); PowerShell 7 is cross-platform |
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.
grep -c "Failed" auth.log
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)(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:
| Principle | What it looks like in practice |
|---|---|
| Scope first | Targets come from an allow-list file you control; the script refuses anything outside it. |
| Dry run | A --dry-run flag prints what would happen without doing it. Make it the default for destructive actions. |
| Fail loudly | Bash: set -euo pipefail. Python: let unexpected exceptions crash with a traceback instead of hiding them. |
| Least privilege | Do not run as root or Administrator unless the step genuinely needs it. |
| No secrets in code | API keys come from environment variables or a secrets manager, never from the script or git. |
| Log what you did | Timestamped logs to a file or stderr, so the 03:00 failure can be explained at 09:00. |
► 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.
$ 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.
- 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.