autopentestx-automated-pentesting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AutoPentestX Automated Pentesting Skill

AutoPentestX 自动化渗透测试工具

Skill by ara.so — Security Skills collection.
AutoPentestX is an automated penetration testing and vulnerability reporting tool built in Python. It streamlines security assessments by automating common pentesting tasks including reconnaissance, scanning, vulnerability detection, and report generation.
ara.so 开发的工具 — 安全工具合集。
AutoPentestX 是一款基于 Python 构建的自动化渗透测试与漏洞报告工具。它通过自动化常见的渗透测试任务(包括侦察、扫描、漏洞检测和报告生成),简化安全评估流程。

Installation

安装

Prerequisites

前置要求

  • Python 3.8 or higher
  • Linux operating system (recommended)
  • Root/sudo privileges for certain scanning features
  • Python 3.8 或更高版本
  • Linux 操作系统(推荐)
  • 部分扫描功能需要 Root/sudo 权限

Basic Installation

基础安装

bash
undefined
bash
undefined

Clone the repository

Clone the repository

Install dependencies

Install dependencies

pip install -r requirements.txt
pip install -r requirements.txt

Make the main script executable

Make the main script executable

chmod +x autopentestx.py
undefined
chmod +x autopentestx.py
undefined

Alternative Installation with Virtual Environment

虚拟环境安装方案

bash
undefined
bash
undefined

Create virtual environment

Create virtual environment

python3 -m venv venv source venv/bin/activate
python3 -m venv venv source venv/bin/activate

Install dependencies

Install dependencies

pip install -r requirements.txt
undefined
pip install -r requirements.txt
undefined

Core Functionality

核心功能

AutoPentestX provides automated security testing capabilities including:
  • Network Reconnaissance: Port scanning, service detection, OS fingerprinting
  • Vulnerability Scanning: Automated detection of common vulnerabilities
  • Web Application Testing: SQL injection, XSS, directory traversal checks
  • Report Generation: Automated PDF/HTML reports with findings
  • Multi-target Support: Scan multiple hosts from target lists
AutoPentestX 提供以下自动化安全测试能力:
  • 网络侦察:端口扫描、服务探测、操作系统指纹识别
  • 漏洞扫描:自动检测常见漏洞
  • Web 应用测试:SQL 注入、XSS、目录遍历检测
  • 报告生成:自动生成包含检测结果的 PDF/HTML 报告
  • 多目标支持:从目标列表中扫描多个主机

Basic Usage

基础使用方法

Running a Basic Scan

运行基础扫描

python
#!/usr/bin/env python3
from autopentestx import AutoPentestX
python
#!/usr/bin/env python3
from autopentestx import AutoPentestX

Initialize the scanner

Initialize the scanner

scanner = AutoPentestX()
scanner = AutoPentestX()

Scan a single target

Scan a single target

target = "192.168.1.100" results = scanner.scan(target)
target = "192.168.1.100" results = scanner.scan(target)

Generate report

Generate report

scanner.generate_report(results, output_format="html")
undefined
scanner.generate_report(results, output_format="html")
undefined

Command Line Interface

命令行界面

bash
undefined
bash
undefined

Basic scan of a single target

Basic scan of a single target

python3 autopentestx.py -t 192.168.1.100
python3 autopentestx.py -t 192.168.1.100

Scan with verbose output

Scan with verbose output

python3 autopentestx.py -t 192.168.1.100 -v
python3 autopentestx.py -t 192.168.1.100 -v

Scan multiple targets from file

Scan multiple targets from file

python3 autopentestx.py -f targets.txt
python3 autopentestx.py -f targets.txt

Specify output format

Specify output format

python3 autopentestx.py -t 192.168.1.100 -o pdf
python3 autopentestx.py -t 192.168.1.100 -o pdf

Run specific modules only

Run specific modules only

python3 autopentestx.py -t 192.168.1.100 -m portscan,vulnscan
undefined
python3 autopentestx.py -t 192.168.1.100 -m portscan,vulnscan
undefined

Configuration

配置

Configuration File Structure

配置文件结构

Create a
config.json
file for persistent settings:
json
{
  "scan_settings": {
    "timeout": 300,
    "threads": 10,
    "rate_limit": 100
  },
  "modules": {
    "port_scan": true,
    "vuln_scan": true,
    "web_scan": true,
    "brute_force": false
  },
  "reporting": {
    "format": "html",
    "output_dir": "./reports",
    "include_screenshots": false
  },
  "network": {
    "user_agent": "AutoPentestX/1.0",
    "proxy": null,
    "verify_ssl": true
  }
}
创建
config.json
文件用于持久化设置:
json
{
  "scan_settings": {
    "timeout": 300,
    "threads": 10,
    "rate_limit": 100
  },
  "modules": {
    "port_scan": true,
    "vuln_scan": true,
    "web_scan": true,
    "brute_force": false
  },
  "reporting": {
    "format": "html",
    "output_dir": "./reports",
    "include_screenshots": false
  },
  "network": {
    "user_agent": "AutoPentestX/1.0",
    "proxy": null,
    "verify_ssl": true
  }
}

Loading Configuration

加载配置

python
import json
from autopentestx import AutoPentestX
python
import json
from autopentestx import AutoPentestX

Load configuration

Load configuration

with open('config.json', 'r') as f: config = json.load(f)
with open('config.json', 'r') as f: config = json.load(f)

Initialize with config

Initialize with config

scanner = AutoPentestX(config=config)
undefined
scanner = AutoPentestX(config=config)
undefined

Advanced Usage Patterns

高级使用模式

Custom Scanning Workflow

自定义扫描工作流

python
from autopentestx import AutoPentestX, ScanModule
python
from autopentestx import AutoPentestX, ScanModule

Initialize scanner

Initialize scanner

scanner = AutoPentestX()
scanner = AutoPentestX()

Configure specific scan parameters

Configure specific scan parameters

scan_config = { 'target': '192.168.1.0/24', 'scan_type': 'comprehensive', 'port_range': '1-65535', 'timeout': 600 }
scan_config = { 'target': '192.168.1.0/24', 'scan_type': 'comprehensive', 'port_range': '1-65535', 'timeout': 600 }

Run reconnaissance

Run reconnaissance

recon_results = scanner.run_module('reconnaissance', scan_config)
recon_results = scanner.run_module('reconnaissance', scan_config)

Perform port scanning

Perform port scanning

port_results = scanner.run_module('port_scan', { 'target': scan_config['target'], 'ports': [21, 22, 80, 443, 3306, 8080] })
port_results = scanner.run_module('port_scan', { 'target': scan_config['target'], 'ports': [21, 22, 80, 443, 3306, 8080] })

Vulnerability assessment

Vulnerability assessment

vuln_results = scanner.run_module('vulnerability_scan', { 'target': scan_config['target'], 'services': port_results['open_ports'] })
vuln_results = scanner.run_module('vulnerability_scan', { 'target': scan_config['target'], 'services': port_results['open_ports'] })

Compile results

Compile results

final_report = scanner.compile_results([ recon_results, port_results, vuln_results ])
final_report = scanner.compile_results([ recon_results, port_results, vuln_results ])

Generate report

Generate report

scanner.generate_report(final_report, format='pdf', output='security_assessment.pdf')
undefined
scanner.generate_report(final_report, format='pdf', output='security_assessment.pdf')
undefined

Web Application Testing

Web 应用测试

python
from autopentestx import WebScanner
python
from autopentestx import WebScanner

Initialize web scanner

Initialize web scanner

web_scanner = WebScanner()
web_scanner = WebScanner()

Configure target

Configure target

target_url = "http://example.com"
target_url = "http://example.com"

SQL Injection testing

SQL Injection testing

sqli_results = web_scanner.test_sql_injection( url=target_url, forms=True, params=True )
sqli_results = web_scanner.test_sql_injection( url=target_url, forms=True, params=True )

XSS testing

XSS testing

xss_results = web_scanner.test_xss( url=target_url, payloads='default' )
xss_results = web_scanner.test_xss( url=target_url, payloads='default' )

Directory traversal

Directory traversal

dir_trav_results = web_scanner.test_directory_traversal( url=target_url )
dir_trav_results = web_scanner.test_directory_traversal( url=target_url )

Generate web-specific report

Generate web-specific report

web_scanner.generate_report({ 'sqli': sqli_results, 'xss': xss_results, 'directory_traversal': dir_trav_results })
undefined
web_scanner.generate_report({ 'sqli': sqli_results, 'xss': xss_results, 'directory_traversal': dir_trav_results })
undefined

Batch Scanning from Target List

从目标列表批量扫描

python
from autopentestx import AutoPentestX
import concurrent.futures
python
from autopentestx import AutoPentestX
import concurrent.futures

Initialize scanner

Initialize scanner

scanner = AutoPentestX()
scanner = AutoPentestX()

Load targets

Load targets

with open('targets.txt', 'r') as f: targets = [line.strip() for line in f if line.strip()]
with open('targets.txt', 'r') as f: targets = [line.strip() for line in f if line.strip()]

Parallel scanning function

Parallel scanning function

def scan_target(target): try: results = scanner.scan(target) return { 'target': target, 'status': 'success', 'results': results } except Exception as e: return { 'target': target, 'status': 'failed', 'error': str(e) }
def scan_target(target): try: results = scanner.scan(target) return { 'target': target, 'status': 'success', 'results': results } except Exception as e: return { 'target': target, 'status': 'failed', 'error': str(e) }

Execute parallel scans

Execute parallel scans

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: scan_results = list(executor.map(scan_target, targets))
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: scan_results = list(executor.map(scan_target, targets))

Aggregate results

Aggregate results

successful_scans = [r for r in scan_results if r['status'] == 'success'] failed_scans = [r for r in scan_results if r['status'] == 'failed']
print(f"Successful: {len(successful_scans)}, Failed: {len(failed_scans)}")
successful_scans = [r for r in scan_results if r['status'] == 'success'] failed_scans = [r for r in scan_results if r['status'] == 'failed']
print(f"Successful: {len(successful_scans)}, Failed: {len(failed_scans)}")

Generate comprehensive report

Generate comprehensive report

scanner.generate_batch_report(successful_scans, output='batch_pentest_report.pdf')
undefined
scanner.generate_batch_report(successful_scans, output='batch_pentest_report.pdf')
undefined

Report Generation

报告生成

Custom Report Templates

自定义报告模板

python
from autopentestx import ReportGenerator
python
from autopentestx import ReportGenerator

Initialize report generator

Initialize report generator

report_gen = ReportGenerator()
report_gen = ReportGenerator()

Define custom template

Define custom template

template_config = { 'title': 'Security Assessment Report', 'sections': [ 'executive_summary', 'methodology', 'findings', 'recommendations', 'appendix' ], 'severity_colors': { 'critical': '#FF0000', 'high': '#FF6600', 'medium': '#FFCC00', 'low': '#00FF00' } }
template_config = { 'title': 'Security Assessment Report', 'sections': [ 'executive_summary', 'methodology', 'findings', 'recommendations', 'appendix' ], 'severity_colors': { 'critical': '#FF0000', 'high': '#FF6600', 'medium': '#FFCC00', 'low': '#00FF00' } }

Generate report with custom template

Generate report with custom template

report_gen.create_report( results=scan_results, template=template_config, output_file='custom_report.pdf' )
undefined
report_gen.create_report( results=scan_results, template=template_config, output_file='custom_report.pdf' )
undefined

Exporting Results to JSON

将结果导出为 JSON

python
import json
from autopentestx import AutoPentestX

scanner = AutoPentestX()
results = scanner.scan('192.168.1.100')
python
import json
from autopentestx import AutoPentestX

scanner = AutoPentestX()
results = scanner.scan('192.168.1.100')

Export to JSON

Export to JSON

with open('scan_results.json', 'w') as f: json.dump(results, f, indent=2)
with open('scan_results.json', 'w') as f: json.dump(results, f, indent=2)

Export specific findings

Export specific findings

vulnerabilities = results.get('vulnerabilities', []) with open('vulnerabilities.json', 'w') as f: json.dump(vulnerabilities, f, indent=2)
undefined
vulnerabilities = results.get('vulnerabilities', []) with open('vulnerabilities.json', 'w') as f: json.dump(vulnerabilities, f, indent=2)
undefined

Environment Variables

环境变量

Configure AutoPentestX using environment variables:
bash
undefined
使用环境变量配置 AutoPentestX:
bash
undefined

Set API keys for integrations (if applicable)

Set API keys for integrations (if applicable)

export AUTOPENTESTX_API_KEY="your_api_key_here"
export AUTOPENTESTX_API_KEY="your_api_key_here"

Configure proxy settings

Configure proxy settings

export AUTOPENTESTX_PROXY="http://proxy.example.com:8080"
export AUTOPENTESTX_PROXY="http://proxy.example.com:8080"

Set report output directory

Set report output directory

export AUTOPENTESTX_OUTPUT_DIR="/var/reports"
export AUTOPENTESTX_OUTPUT_DIR="/var/reports"

Configure logging level

Configure logging level

export AUTOPENTESTX_LOG_LEVEL="DEBUG"
export AUTOPENTESTX_LOG_LEVEL="DEBUG"

Set scan timeout

Set scan timeout

export AUTOPENTESTX_TIMEOUT="600"
undefined
export AUTOPENTESTX_TIMEOUT="600"
undefined

Using Environment Variables in Code

在代码中使用环境变量

python
import os
from autopentestx import AutoPentestX
python
import os
from autopentestx import AutoPentestX

Initialize with environment variables

Initialize with environment variables

scanner = AutoPentestX( api_key=os.getenv('AUTOPENTESTX_API_KEY'), proxy=os.getenv('AUTOPENTESTX_PROXY'), output_dir=os.getenv('AUTOPENTESTX_OUTPUT_DIR', './reports'), timeout=int(os.getenv('AUTOPENTESTX_TIMEOUT', '300')) )
undefined
scanner = AutoPentestX( api_key=os.getenv('AUTOPENTESTX_API_KEY'), proxy=os.getenv('AUTOPENTESTX_PROXY'), output_dir=os.getenv('AUTOPENTESTX_OUTPUT_DIR', './reports'), timeout=int(os.getenv('AUTOPENTESTX_TIMEOUT', '300')) )
undefined

Common Patterns

常见使用模式

Safe Scanning with Rate Limiting

带速率限制的安全扫描

python
from autopentestx import AutoPentestX
import time

scanner = AutoPentestX()
python
from autopentestx import AutoPentestX
import time

scanner = AutoPentestX()

Configure rate limiting

Configure rate limiting

scanner.set_rate_limit(requests_per_second=10)
scanner.set_rate_limit(requests_per_second=10)

Scan with delays

Scan with delays

targets = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] for target in targets: results = scanner.scan(target) print(f"Scanned {target}") time.sleep(2) # Additional delay between targets
undefined
targets = ['192.168.1.1', '192.168.1.2', '192.168.1.3'] for target in targets: results = scanner.scan(target) print(f"Scanned {target}") time.sleep(2) # Additional delay between targets
undefined

Error Handling and Logging

错误处理与日志记录

python
import logging
from autopentestx import AutoPentestX, ScanException
python
import logging
from autopentestx import AutoPentestX, ScanException

Configure logging

Configure logging

logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('autopentestx.log'), logging.StreamHandler() ] )
logger = logging.getLogger('AutoPentestX')
logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('autopentestx.log'), logging.StreamHandler() ] )
logger = logging.getLogger('AutoPentestX')

Initialize scanner

Initialize scanner

scanner = AutoPentestX()
scanner = AutoPentestX()

Scan with error handling

Scan with error handling

try: results = scanner.scan('192.168.1.100') logger.info("Scan completed successfully") except ScanException as e: logger.error(f"Scan failed: {e}") except Exception as e: logger.critical(f"Unexpected error: {e}") finally: scanner.cleanup()
undefined
try: results = scanner.scan('192.168.1.100') logger.info("Scan completed successfully") except ScanException as e: logger.error(f"Scan failed: {e}") except Exception as e: logger.critical(f"Unexpected error: {e}") finally: scanner.cleanup()
undefined

Integrating with CI/CD Pipelines

与 CI/CD 流水线集成

python
#!/usr/bin/env python3
import sys
from autopentestx import AutoPentestX

def ci_security_scan(target, fail_on_high=True):
    """
    Run security scan suitable for CI/CD integration
    """
    scanner = AutoPentestX()
    
    # Run scan
    results = scanner.scan(target)
    
    # Generate report
    scanner.generate_report(results, format='json', output='ci_scan_results.json')
    
    # Check severity levels
    vulnerabilities = results.get('vulnerabilities', [])
    high_severity = [v for v in vulnerabilities if v['severity'] in ['critical', 'high']]
    
    if high_severity and fail_on_high:
        print(f"FAILURE: Found {len(high_severity)} high/critical vulnerabilities")
        sys.exit(1)
    else:
        print(f"SUCCESS: Scan completed. Found {len(vulnerabilities)} total findings")
        sys.exit(0)

if __name__ == '__main__':
    target = sys.argv[1] if len(sys.argv) > 1 else 'localhost'
    ci_security_scan(target)
python
#!/usr/bin/env python3
import sys
from autopentestx import AutoPentestX

def ci_security_scan(target, fail_on_high=True):
    """
    运行适用于 CI/CD 集成的安全扫描
    """
    scanner = AutoPentestX()
    
    # Run scan
    results = scanner.scan(target)
    
    # Generate report
    scanner.generate_report(results, format='json', output='ci_scan_results.json')
    
    # Check severity levels
    vulnerabilities = results.get('vulnerabilities', [])
    high_severity = [v for v in vulnerabilities if v['severity'] in ['critical', 'high']]
    
    if high_severity and fail_on_high:
        print(f"FAILURE: Found {len(high_severity)} high/critical vulnerabilities")
        sys.exit(1)
    else:
        print(f"SUCCESS: Scan completed. Found {len(vulnerabilities)} total findings")
        sys.exit(0)

if __name__ == '__main__':
    target = sys.argv[1] if len(sys.argv) > 1 else 'localhost'
    ci_security_scan(target)

Troubleshooting

故障排除

Common Issues and Solutions

常见问题与解决方案

Permission Denied Errors
bash
undefined
权限拒绝错误
bash
undefined

Run with sudo for privileged operations

Run with sudo for privileged operations

sudo python3 autopentestx.py -t 192.168.1.100
sudo python3 autopentestx.py -t 192.168.1.100

Or adjust capabilities for specific binaries

Or adjust capabilities for specific binaries

sudo setcap cap_net_raw+ep /usr/bin/python3

**Timeout Issues**
```python
sudo setcap cap_net_raw+ep /usr/bin/python3

**超时问题**
```python

Increase timeout for slow networks

Increase timeout for slow networks

scanner = AutoPentestX(timeout=900)
scanner = AutoPentestX(timeout=900)

Or configure per-module timeouts

Or configure per-module timeouts

scanner.set_module_timeout('port_scan', 600)

**Missing Dependencies**
```bash
scanner.set_module_timeout('port_scan', 600)

**依赖缺失**
```bash

Install system dependencies

Install system dependencies

sudo apt-get update sudo apt-get install nmap masscan nikto
sudo apt-get update sudo apt-get install nmap masscan nikto

Reinstall Python dependencies

Reinstall Python dependencies

pip install -r requirements.txt --force-reinstall

**Network Connectivity Problems**
```python
pip install -r requirements.txt --force-reinstall

**网络连接问题**
```python

Test connectivity before scanning

Test connectivity before scanning

from autopentestx.utils import check_connectivity
if check_connectivity('192.168.1.100'): results = scanner.scan('192.168.1.100') else: print("Target unreachable")

**Memory Issues with Large Scans**
```python
from autopentestx.utils import check_connectivity
if check_connectivity('192.168.1.100'): results = scanner.scan('192.168.1.100') else: print("Target unreachable")

**大规模扫描内存问题**
```python

Enable memory-efficient mode

Enable memory-efficient mode

scanner = AutoPentestX(memory_efficient=True)
scanner = AutoPentestX(memory_efficient=True)

Or process results in chunks

Or process results in chunks

scanner.set_chunk_size(100)
undefined
scanner.set_chunk_size(100)
undefined

Best Practices

最佳实践

  1. Always obtain proper authorization before scanning any systems
  2. Use rate limiting to avoid overwhelming target systems
  3. Store reports securely with appropriate access controls
  4. Validate targets before initiating scans
  5. Review results manually - automated tools may have false positives
  6. Keep the tool updated for latest vulnerability checks
  7. Use configuration files for consistent scanning parameters
  8. Log all activities for audit trails and debugging
  1. 扫描任何系统前务必获得合法授权
  2. 使用速率限制,避免压垮目标系统
  3. 安全存储报告,设置适当的访问控制
  4. 扫描前验证目标
  5. 手动复核结果——自动化工具可能存在误报
  6. 保持工具更新,以检测最新漏洞
  7. 使用配置文件确保扫描参数一致
  8. 记录所有活动,用于审计追踪和调试

Integration Examples

集成示例

Integration with Metasploit

与 Metasploit 集成

python
from autopentestx import AutoPentestX
from pymetasploit3.msfrpc import MsfRpcClient
python
from autopentestx import AutoPentestX
from pymetasploit3.msfrpc import MsfRpcClient

Run initial scan

Run initial scan

scanner = AutoPentestX() results = scanner.scan('192.168.1.100')
scanner = AutoPentestX() results = scanner.scan('192.168.1.100')

Extract exploitable vulnerabilities

Extract exploitable vulnerabilities

exploitable = [v for v in results['vulnerabilities'] if v.get('exploitable')]
exploitable = [v for v in results['vulnerabilities'] if v.get('exploitable')]

Connect to Metasploit

Connect to Metasploit

client = MsfRpcClient(os.getenv('MSF_RPC_PASSWORD'), server='127.0.0.1')
client = MsfRpcClient(os.getenv('MSF_RPC_PASSWORD'), server='127.0.0.1')

Exploit findings

Exploit findings

for vuln in exploitable: exploit = client.modules.use('exploit', vuln['exploit_path']) exploit['RHOSTS'] = vuln['target'] exploit.execute()
undefined
for vuln in exploitable: exploit = client.modules.use('exploit', vuln['exploit_path']) exploit['RHOSTS'] = vuln['target'] exploit.execute()
undefined

Webhook Notifications

Webhook 通知

python
import requests
from autopentestx import AutoPentestX

scanner = AutoPentestX()
results = scanner.scan('192.168.1.100')
python
import requests
from autopentestx import AutoPentestX

scanner = AutoPentestX()
results = scanner.scan('192.168.1.100')

Send results to webhook

Send results to webhook

webhook_url = os.getenv('WEBHOOK_URL') payload = { 'target': '192.168.1.100', 'vulnerabilities_found': len(results['vulnerabilities']), 'severity_summary': results['severity_summary'] }
requests.post(webhook_url, json=payload)
undefined
webhook_url = os.getenv('WEBHOOK_URL') payload = { 'target': '192.168.1.100', 'vulnerabilities_found': len(results['vulnerabilities']), 'severity_summary': results['severity_summary'] }
requests.post(webhook_url, json=payload)
undefined