Automation

Objectives: By the end of this topic, you will be able to…

  • Create scripts in Bash or Python to automate security tasks
  • Integrate Kali tools into functional scripts
  • Read, process, and filter results from other tools
  • Use scripting to support reconnaissance, analysis, and defense

Introduction to Bash and Python scripting for security

Scripting is an essential skill in cybersecurity for automating repetitive tasks, creating custom tools, and responding quickly to incidents. Bash is ideal for system automation: interacting with command-line tools, manipulating files, and chaining commands together in the shell. Python offers more flexibility and readability for tasks that require data processing, API interaction, log analysis, or more complex logic. Both languages are extensively used in offensive and defensive security.


Automating repetitive tasks

In Bash

Bash excels at tasks that are already expressed as shell commands: running nmap across multiple IP ranges, filtering log files with grep, awk, and sed, downloading batches of URLs with curl or wget, and monitoring files or processes in real time. Its strength is the ability to compose existing tools into pipelines with minimal boilerplate.

In Python

Python handles tasks where Bash starts to struggle: parsing structured .log or .pcap files, automating API calls to services like VirusTotal or Shodan, post-processing and enriching output from scanners like nmap or nikto, generating formatted reports or automated alerts, and building vulnerability exploitation wrappers that require conditional logic or network interactions beyond what shell pipes can express cleanly.


Best practices in security scripting

Good security scripts follow a consistent set of principles grouped by concern. For code quality, include clear comments that explain why the script does what it does, and document expected inputs and outputs so that someone else can maintain it. For safety, never trust parameters without sanitizing them first, and store credentials in environment variables or configuration files rather than hardcoding them into the script where they might end up in version control. For reliability, implement explicit error handling so the script fails loudly rather than silently continuing in a broken state, and log all significant actions, errors, and results in a readable format for later review. For portability, avoid unnecessary dependencies and absolute paths, and understand what privileges the script requires — run with the minimum needed to accomplish the task.


Examples of tool integration

Bash: extract IPs with port 22 open

nmap -p 22 --open -oG - 192.168.1.0/24 | grep '/open/' | awk '{print $2}'

Python: send URLs to an API

import requests
 
urls = ['http://example.com', 'http://test.com']
for url in urls:
    response = requests.get(f'https://urlscan.io/api/v1/scan/', params={'url': url})
    print(response.json())

Bash: extract domains from a file

cat file.txt | grep -Eo 'https?://[^/"]+' | sort -u

Python: run nmap via subprocess

import subprocess
 
result = subprocess.run(['nmap', '-sS', '192.168.0.1'], capture_output=True, text=True)
print(result.stdout)

Hands-on lab

Requirements: Kali Linux, Python 3, command-line tools

Part 1: Basic network scripting

A. Local network scanning in Bash:

#!/bin/bash
echo "Scanning local network 192.168.1.0/24..."
for ip in $(seq 1 254); do
    (ping -c 1 -W 1 192.168.1.$ip | grep "64 bytes" && echo "192.168.1.$ip is active") &
done
wait

Tasks: save output to file, add response time and timestamp.

? How does parallelizing the pings with & and wait affect performance compared to a sequential loop? What are the tradeoffs in terms of network load and result accuracy?

B. Python script for nmap scanning:

import subprocess
import sys
 
target = sys.argv[1] if len(sys.argv) > 1 else "192.168.1.1"
print(f"Scanning all ports on {target}...")
 
result = subprocess.run(["nmap", "-p-", target], capture_output=True, text=True)
with open(f"nmap_{target}.txt", "w") as f:
    f.write(result.stdout)

Tasks: use argparse for target IP and output file, detect and list open ports separately.

? How does your script handle hosts that are unreachable or that take a long time to respond? What would happen if nmap returns a non-zero exit code for a given target?

Part 2: Information gathering automation

Create a script that:

  1. Receives a domain as argument
  2. Executes whois, dig, nslookup, host, curl -I
  3. Extracts A and MX records with dig and saves them

? From the whois and DNS output you collected, what information would be most useful to an attacker in the early reconnaissance phase? What data should organizations minimize in their public DNS records?

Part 3: Mini-project (choose one)

Option A: Network scan with latency

  • Record active IPs and response time, save in CSV format

Option B: Apache log analysis

  • Read access.log, search for SQL commands, 403/500 status codes, IPs with multiple failed attempts
  • Save suspicious IPs and hourly summary

Option C: Automated web profiling

  • Receive a domain, run nmap, whois, whatweb
  • Generate report with open ports, detected technologies, domain owner

? How does your script handle errors — such as an unreachable host or a tool that is not installed? What is the difference between silently ignoring an error and logging it for later review?

Submission

Compressed folder with:

  • Functional and commented scripts
  • Generated results (txt/csv)
  • README.md with: explanation of each script, what it automates, execution instructions

Key concepts

TermDefinition
BashDefault command interpreter and scripting language on Linux
PythonVersatile programming language used for security automation
subprocessPython module for executing system commands
argparsePython module for parsing command-line arguments
ScriptingWriting short programs to automate repetitive tasks

Navigation:Previous | Home | Next