autopentestx-automated-pentesting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAutoPentestX 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
undefinedbash
undefinedClone the repository
Clone the repository
git clone https://github.com/Gowtham-Darkseid/AutoPentestX.git
cd AutoPentestX
git clone https://github.com/Gowtham-Darkseid/AutoPentestX.git
cd AutoPentestX
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
undefinedchmod +x autopentestx.py
undefinedAlternative Installation with Virtual Environment
虚拟环境安装方案
bash
undefinedbash
undefinedCreate 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
undefinedpip install -r requirements.txt
undefinedCore 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 AutoPentestXpython
#!/usr/bin/env python3
from autopentestx import AutoPentestXInitialize 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")
undefinedscanner.generate_report(results, output_format="html")
undefinedCommand Line Interface
命令行界面
bash
undefinedbash
undefinedBasic 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
undefinedpython3 autopentestx.py -t 192.168.1.100 -m portscan,vulnscan
undefinedConfiguration
配置
Configuration File Structure
配置文件结构
Create a file for persistent settings:
config.jsonjson
{
"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.jsonjson
{
"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 AutoPentestXpython
import json
from autopentestx import AutoPentestXLoad 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)
undefinedscanner = AutoPentestX(config=config)
undefinedAdvanced Usage Patterns
高级使用模式
Custom Scanning Workflow
自定义扫描工作流
python
from autopentestx import AutoPentestX, ScanModulepython
from autopentestx import AutoPentestX, ScanModuleInitialize 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')
undefinedscanner.generate_report(final_report, format='pdf', output='security_assessment.pdf')
undefinedWeb Application Testing
Web 应用测试
python
from autopentestx import WebScannerpython
from autopentestx import WebScannerInitialize 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
})
undefinedweb_scanner.generate_report({
'sqli': sqli_results,
'xss': xss_results,
'directory_traversal': dir_trav_results
})
undefinedBatch Scanning from Target List
从目标列表批量扫描
python
from autopentestx import AutoPentestX
import concurrent.futurespython
from autopentestx import AutoPentestX
import concurrent.futuresInitialize 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')
undefinedscanner.generate_batch_report(successful_scans, output='batch_pentest_report.pdf')
undefinedReport Generation
报告生成
Custom Report Templates
自定义报告模板
python
from autopentestx import ReportGeneratorpython
from autopentestx import ReportGeneratorInitialize 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'
)
undefinedreport_gen.create_report(
results=scan_results,
template=template_config,
output_file='custom_report.pdf'
)
undefinedExporting 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)
undefinedvulnerabilities = results.get('vulnerabilities', [])
with open('vulnerabilities.json', 'w') as f:
json.dump(vulnerabilities, f, indent=2)
undefinedEnvironment Variables
环境变量
Configure AutoPentestX using environment variables:
bash
undefined使用环境变量配置 AutoPentestX:
bash
undefinedSet 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"
undefinedexport AUTOPENTESTX_TIMEOUT="600"
undefinedUsing Environment Variables in Code
在代码中使用环境变量
python
import os
from autopentestx import AutoPentestXpython
import os
from autopentestx import AutoPentestXInitialize 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'))
)
undefinedscanner = 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'))
)
undefinedCommon 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
undefinedtargets = ['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
undefinedError Handling and Logging
错误处理与日志记录
python
import logging
from autopentestx import AutoPentestX, ScanExceptionpython
import logging
from autopentestx import AutoPentestX, ScanExceptionConfigure 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()
undefinedtry:
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()
undefinedIntegrating 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
undefinedRun 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**
```pythonsudo setcap cap_net_raw+ep /usr/bin/python3
**超时问题**
```pythonIncrease 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**
```bashscanner.set_module_timeout('port_scan', 600)
**依赖缺失**
```bashInstall 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**
```pythonpip install -r requirements.txt --force-reinstall
**网络连接问题**
```pythonTest 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**
```pythonfrom autopentestx.utils import check_connectivity
if check_connectivity('192.168.1.100'):
results = scanner.scan('192.168.1.100')
else:
print("Target unreachable")
**大规模扫描内存问题**
```pythonEnable 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)
undefinedscanner.set_chunk_size(100)
undefinedBest Practices
最佳实践
- Always obtain proper authorization before scanning any systems
- Use rate limiting to avoid overwhelming target systems
- Store reports securely with appropriate access controls
- Validate targets before initiating scans
- Review results manually - automated tools may have false positives
- Keep the tool updated for latest vulnerability checks
- Use configuration files for consistent scanning parameters
- Log all activities for audit trails and debugging
- 扫描任何系统前务必获得合法授权
- 使用速率限制,避免压垮目标系统
- 安全存储报告,设置适当的访问控制
- 扫描前验证目标
- 手动复核结果——自动化工具可能存在误报
- 保持工具更新,以检测最新漏洞
- 使用配置文件确保扫描参数一致
- 记录所有活动,用于审计追踪和调试
Integration Examples
集成示例
Integration with Metasploit
与 Metasploit 集成
python
from autopentestx import AutoPentestX
from pymetasploit3.msfrpc import MsfRpcClientpython
from autopentestx import AutoPentestX
from pymetasploit3.msfrpc import MsfRpcClientRun 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()
undefinedfor vuln in exploitable:
exploit = client.modules.use('exploit', vuln['exploit_path'])
exploit['RHOSTS'] = vuln['target']
exploit.execute()
undefinedWebhook 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)
undefinedwebhook_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