# Pentest MCP Server Examples

This directory contains practical examples demonstrating how to use the Pentest MCP Server.

## 📋 Available Examples

### 1. Basic Network Scan (`basic_scan.py`)
**Demonstrates:** Session creation, command execution with triggers, output parsing

Simple nmap scan with automatic completion detection and XML parsing.

```bash
python basic_scan.py 192.168.1.0/24
```

**Features shown:**
- Creating persistent tmux sessions
- Executing commands with trigger-based monitoring
- Waiting for scan completion automatically
- Parsing nmap XML output
- Proper session cleanup

---

### 2. Web Application Enumeration (`web_enum.py`)
**Demonstrates:** Parallel operations, background execution, session monitoring

Runs gobuster for directory enumeration and nikto for vulnerability scanning.

```bash
python web_enum.py http://192.168.1.100
```

**Features shown:**
- Multiple concurrent sessions
- Foreground execution with triggers (gobuster)
- Background execution (nikto)
- Reading output from running sessions
- Monitoring scan progress

---

### 3. Parallel Scanning (`parallel_scans.py`)
**Demonstrates:** Multiple simultaneous scans, resource management, progress monitoring

Scans multiple targets in parallel and monitors progress.

```bash
python parallel_scans.py 192.168.1.1 192.168.1.2 192.168.1.3
```

**Features shown:**
- Creating multiple sessions
- Starting all scans simultaneously
- Periodic progress monitoring
- System status checking
- Parsing results from multiple scans

---

## 🚀 Quick Start

### Prerequisites

1. **Install the package:**
```bash
cd ..
pip install -e .
```

2. **Configure environment:**
```bash
cp ../.env.example ../.env
# Edit .env with your Kali Linux details
```

3. **Ensure target system is accessible:**
```bash
# Test SSH connection
ssh kali@<TARGET_HOST>

# Ensure tmux is installed on target
sudo apt update && sudo apt install tmux
```

### Running Examples

All examples follow the same pattern:

```bash
# Make executable (Linux/Mac)
chmod +x *.py

# Run example
python <example_name>.py <arguments>
```

---

## 📚 Example Walkthroughs

### Example 1: Basic Scan Walkthrough

```bash
python basic_scan.py 192.168.1.0/24
```

**What happens:**
1. Creates a session called "basic_scan"
2. Executes nmap with `-sV` (service version detection)
3. Monitors output until "Nmap done" appears
4. Parses the XML results
5. Displays found hosts and open ports
6. Cleans up the session

**Expected output:**
```
[*] Starting basic network scan of 192.168.1.0/24
[+] Creating scan session...
[+] Session created: basic_scan

[*] Running nmap scan on 192.168.1.0/24...
[+] Scan completed in 45.23 seconds
[+] Trigger matched: scan_complete

[*] Parsing scan results...
[+] Found 5 host(s)

Host #1: 192.168.1.1
  Open ports: 3
    - 22/tcp: ssh (open)
    - 80/tcp: http (open)
    - 443/tcp: https (open)
...
```

---

### Example 2: Web Enumeration Walkthrough

```bash
python web_enum.py http://192.168.1.100
```

**What happens:**
1. Creates two sessions: "gobuster" and "nikto"
2. Runs gobuster in foreground (waits for completion)
3. Starts nikto in background (continues immediately)
4. Shows gobuster findings
5. Monitors nikto progress
6. Lists all active sessions

**Expected output:**
```
[*] Starting web application enumeration of http://192.168.1.100
[+] Creating sessions...
  ✓ gobuster: Directory enumeration
  ✓ nikto: Vulnerability scanning

[*] Starting directory enumeration with gobuster...
[+] Gobuster completed in 23.45 seconds

[*] Found directories and files:
------------------------------------------------------------
  /admin                (Status: 200) [Size: 1234]
  /login                (Status: 200) [Size: 2345]
  /uploads              (Status: 301) [Size: 0]
...

[*] Starting nikto vulnerability scan (background)...
[+] Nikto scan started in background
```

---

### Example 3: Parallel Scans Walkthrough

```bash
python parallel_scans.py 192.168.1.1 192.168.1.2 192.168.1.3
```

**What happens:**
1. Creates a session for each target (scan_1, scan_2, scan_3)
2. Starts all scans simultaneously in background
3. Monitors progress every 5 seconds
4. Shows completion status
5. Parses and displays results from completed scans

**Expected output:**
```
[*] Starting parallel scans of 3 target(s)
[+] Creating sessions...
  ✓ scan_1: 192.168.1.1
  ✓ scan_2: 192.168.1.2
  ✓ scan_3: 192.168.1.3

[*] Starting scans in background...
  ✓ scan_1: Scan started for 192.168.1.1
  ✓ scan_2: Scan started for 192.168.1.2
  ✓ scan_3: Scan started for 192.168.1.3

[*] Monitoring scan progress...
  [scan_1] Progress: Nmap scan report for 192.168.1.1...
  [scan_2] Progress: Discovered open port 22/tcp on 192.168.1.2...
  [scan_3] Scan completed!
...
```

---

## 🎓 Learning Path

**Recommended order for learning:**

1. **Start with `basic_scan.py`**
   - Learn session management
   - Understand triggers
   - See output parsing

2. **Move to `web_enum.py`**
   - Learn parallel operations
   - Understand background execution
   - Practice session monitoring

3. **Master `parallel_scans.py`**
   - Handle multiple targets
   - Monitor concurrent operations
   - Manage system resources

---

## 🔧 Customization

### Modifying Scan Parameters

**Change nmap options:**
```python
# In basic_scan.py, line ~45
"command": f"nmap -sV {target} -oX /tmp/basic_scan.xml",

# Change to:
"command": f"nmap -sS -p- {target} -oX /tmp/basic_scan.xml",  # Full port scan
"command": f"nmap -A {target} -oX /tmp/basic_scan.xml",       # Aggressive scan
```

**Adjust timeouts:**
```python
# In any example
"triggers": [
    {"type": "regex", "pattern": "Nmap done", "name": "scan_complete"},
    {"type": "timeout", "timeout_seconds": 600}  # Change this value
],
"max_timeout": 600  # And this one
```

### Adding New Tools

**Example: Add masscan to parallel_scans.py:**

```python
# Instead of nmap:
"command": f"masscan {target} -p1-65535 --rate=1000 -oX /tmp/{session_id}.xml",

# Then parse with:
parse_result = await server._handle_parse_tool_output({
    "tool": "masscan",  # Changed from "nmap"
    "file_path": f"/tmp/{session_id}.xml",
    "format": "xml"
})
```

---

## 🐛 Troubleshooting

### Common Issues

**1. Connection Failed**
```
Error: Connection failed: [Errno 111] Connection refused
```
**Solution:** Check your `.env` file and ensure SSH is running on target:
```bash
ssh kali@<TARGET_HOST>
service ssh status
```

**2. Tmux Not Found**
```
Error: tmux is not installed on target system
```
**Solution:** Install tmux on target:
```bash
ssh kali@<TARGET_HOST>
sudo apt update && sudo apt install tmux
```

**3. Tool Not Found**
```
bash: nmap: command not found
```
**Solution:** Install the required tool:
```bash
apt install nmap gobuster nikto
```

**4. Timeout Errors**
```
Scan timed out after 300.00 seconds
```
**Solution:** Increase the timeout values or reduce scan scope:
```python
"max_timeout": 1200,  # Increase to 20 minutes
"triggers": [
    {"type": "timeout", "timeout_seconds": 1200}
]
```

---

## 💡 Tips & Best Practices

### Performance Tips

1. **Use background execution for long scans:**
```python
"background": True  # Don't wait for completion
```

2. **Limit parallel operations:**
```python
# Don't run too many heavy scans simultaneously
# The server has MAX_HEAVY_TASKS=3 by default
```

3. **Use specific port ranges:**
```python
# Instead of full port scan:
"command": "nmap -p 22,80,443,3306,5432 192.168.1.1"
```

### Security Tips

1. **Always cleanup sessions:**
```python
finally:
    await server._handle_kill_session({"session_id": "scan"})
    await server.shutdown()
```

2. **Use output files:**
```python
# Save results to files for later analysis
"command": "nmap -sV 192.168.1.1 -oX /tmp/results.xml -oN /tmp/results.txt"
```

3. **Monitor resource usage:**
```python
status = await server._handle_get_system_status({})
print(f"Active sessions: {status['active_sessions']}")
```

---

## 📖 Documentation

- **Main README:** `../README.md` - Full documentation
- **Install Guide:** `../INSTALL.md` - Setup instructions
- **Deployment Checklist:** `../DEPLOYMENT.md` - Production readiness
- **Tests:** `../tests/` - More usage patterns

---

## 🤝 Contributing Examples

Have a useful example? Contribute it!

1. Create your example script
2. Follow the existing format
3. Add documentation to this README
4. Test thoroughly
5. Submit a pull request

---

## ⚠️ Legal Notice

These examples are for **authorized security testing only**. Always ensure you have proper authorization before scanning any systems.

**Never use these tools against systems you don't own or have explicit permission to test.**

---

**Happy Pentesting! 🔒🔓**
