🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Cybersecurity › Scripting for Cybersecurity › Lesson 8
TEC-CYBE44-05 · Lesson 8 · 14 clock hours · lab

Automating Nmap and Other CLI Security Tools with Python and Bash

Objective. Students write scripts that invoke nmap and other CLI security tools as subprocesses, parse their output, and produce structured reports.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Automate Security Tools?

Security professionals run tools like nmap and nikto repeatedly — against dozens of hosts, on a schedule, or as part of a larger workflow. Typing commands by hand every time introduces errors and wastes time. Scripts let you invoke the same tool consistently, capture its output, and feed results into the next step automatically. This lesson teaches you to control command-line (CLI) security tools from Python and Bash, parse their structured output, and produce reports that teammates and auditors can read.

Lab Safety and Authorization

Before running any scan, confirm you have written authorization for every target. Scanning systems you do not own or have not been given explicit permission to test is illegal under the Computer Fraud and Abuse Act (CFAA) and similar state laws. In this course, all scanning must stay inside the designated lab network. Never point these scripts at the internet or at any host outside the lab range. Treat lab credentials like real credentials — do not share them or post them to public repositories.

Running CLI Tools as Subprocesses in Python

Python's `subprocess` module lets a script launch an external program, wait for it to finish, and capture its output. The recommended function for most use cases is `subprocess.run()`.

```python

import subprocess

result = subprocess.run(

["nmap", "-sV", "-oX", "scan.xml", "192.168.10.0/24"],

capture_output=True,

text=True

)

print(result.stdout)

```

Key parameters:

Always use a list for `args` rather than `shell=True` with a string. The `shell=True` option can expose scripts to injection if any part of the command comes from user input.

Nmap XML Output and Parsing

Nmap's `-oX <file>` flag writes results in XML. XML is machine-readable and far easier to parse than plain text. Python's standard library includes `xml.etree.ElementTree` for XML parsing — no extra packages needed.

A typical workflow:

1. Run nmap with `-oX scan.xml`.

2. Load the file: `tree = ET.parse("scan.xml")`

3. Get the root element: `root = tree.getroot()`

4. Iterate over `<host>` elements, then `<port>` children, to extract IP addresses, port numbers, protocols, and service names.

The nmap XML schema uses elements like `<host>`, `<address>`, `<ports>`, `<port>`, and `<state>`. Checking `state.get('state') == 'open'` filters for open ports only.

Bash Wrapper Scripts

Bash is well-suited for gluing tools together in a pipeline. A wrapper script for this lab should:

1. Accept a subnet as an argument (e.g., `$1`).

2. Create a timestamped output directory: `OUTDIR="results_$(date +%Y%m%d_%H%M%S)"`.

3. Run nmap against the subnet, saving output to that directory.

4. Parse nmap's output (using `grep` or a helper script) to find hosts with ports 80 or 443 open.

5. Loop over those hosts and run nikto against each, redirecting output to per-host files in the same directory.

6. Write an `index.txt` listing all result files with timestamps.

Always quote variables in Bash (`"$1"`, `"$OUTDIR"`) to handle spaces and special characters safely. Add a usage check at the top:

```bash

if [ $# -lt 1 ]; then

echo "Usage: $0 <subnet>"

exit 1

fi

```

Documenting with README.md and Git

A script without documentation is a security risk — someone may run it incorrectly or on the wrong target. Your README.md must include:

Store everything in a local Git repository. Commit frequently and write meaningful commit messages that describe what changed. The course requires at least three commits showing iterative development — not three commits of the same file with cosmetic changes. Good messages: `"Add subnet argument validation"`, `"Parse nmap XML for web ports"`, `"Add nikto loop and index file generation"`.

Connecting to Security+ Objectives

Network scanning and enumeration appear in the CompTIA Security+ exam objectives under threat intelligence and vulnerability assessment topics. Understanding how attackers use tools like nmap — and how defenders detect and respond to scans — is core knowledge. Writing these scripts from a defender's perspective gives you practical insight into what scan traffic looks like on the wire and what logs it generates.

Key terms8

subprocess.run()A Python standard-library function that executes an external command, waits for it to complete, and returns the exit code along with captured stdout and stderr.
nmap XML output (-oX)An nmap flag that writes scan results in XML format to a specified file, making output easy to parse programmatically.
xml.etree.ElementTreeA Python standard-library module for parsing and navigating XML documents using a tree of Element objects.
niktoAn open-source command-line web server scanner that checks for known vulnerabilities, misconfigurations, and outdated software on HTTP and HTTPS services.
shell injectionA vulnerability that occurs when untrusted input is passed to a shell command as a string, allowing an attacker to execute unintended commands; avoided by passing args as a list to subprocess rather than using shell=True.
wrapper scriptA script whose primary job is to invoke one or more other programs, handle their inputs and outputs, and coordinate them into a larger workflow.
timestamped output directoryA directory whose name includes a date-time string (e.g., results_20240915_143022) so that successive script runs do not overwrite previous results.
Computer Fraud and Abuse Act (CFAA)A US federal law that criminalizes unauthorized access to computer systems, making it illegal to scan or probe systems without explicit permission from the owner.
In class: Instructor demo: run nmap with XML output (-oX) against a lab target from a Python script using subprocess.run, then parse the XML with Python's xml.etree.ElementTree to extract host status and open port information. · Lab exercise: students build a Bash wrapper script that calls nmap on a subnet, calls nikto against each discovered web server (ports 80 and 443), and aggregates both outputs into a single timestamped directory with an index file listing all results. · Documentation exercise: students write a README.md for their wrapper script including purpose, prerequisites, usage syntax with examples, and a known-limitations section — stored in a local Git repository with at least three commits showing iterative development.
Materials: Ubuntu VM, nmap, nikto, Git, VS Code, Python xml.etree.ElementTree docs, course lab guide chapter 8, CompTIA Security+ objectives (network scanning and enumeration)
Check: Python script correctly extracts host and port data from nmap XML matching instructor answer key; Bash wrapper produces the indexed directory structure; Git log shows at least three commits; pass requires all three elements.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Threats, Attacks and Vulnerabilities
1. A student wants to run nmap from a Python script and capture its output without risking shell injection. Which subprocess.run() call is safest?
Architecture and Design
2. Which nmap flag saves scan results in XML format to a file called output.xml?
Operations and Incident Response
3. After parsing nmap XML with xml.etree.ElementTree, a student needs to list only open ports. Which element attribute should be checked?
Implementation
4. A Bash wrapper script should validate that the user supplied a subnet argument before running nmap. Which snippet correctly exits with an error message when no argument is given?
Governance, Risk and Compliance
5. A student scans a classmate's personal laptop on the college's general Wi-Fi network during lab time without permission. Which law most directly makes this action illegal in the United States?
Threats, Attacks and Vulnerabilities
6. What is the primary purpose of nikto in the lab workflow?
Operations and Incident Response
7. A student's Git log shows three commits with messages: 'initial commit', 'initial commit 2', and 'final'. The instructor rejects this. What is the most likely reason?
Operations and Incident Response
8. Which section of a README.md would inform a user that the wrapper script cannot perform UDP scans and that nikto scans may take several minutes per host?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.