guardian-cli-ai-pentest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Guardian CLI - AI-Powered Penetration Testing

Guardian CLI - 基于AI的渗透测试

Skill by ara.so — Devtools Skills collection.
Guardian is an enterprise-grade AI-powered penetration testing automation framework that combines multiple AI providers (OpenAI GPT-4, Claude, Google Gemini, OpenRouter) with 19+ security tools to deliver intelligent, adaptive security assessments with comprehensive evidence capture.
ara.so开发的技能 — 属于Devtools Skills合集。
Guardian是一款企业级AI驱动的渗透测试自动化框架,它结合了多个AI提供商(OpenAI GPT-4、Claude、Google Gemini、OpenRouter)与19+款安全工具,可提供智能、自适应的安全评估,并支持全面的证据捕获。

Installation

安装

Prerequisites

前置要求

  • Python 3.11 or higher
  • AI Provider API Key (OpenAI, Anthropic, Google AI Studio, or OpenRouter)
  • Git
  • Python 3.11或更高版本
  • AI提供商API密钥(OpenAI、Anthropic、Google AI Studio或OpenRouter)
  • Git

Basic Installation

基础安装

bash
undefined
bash
undefined

Clone the repository

克隆仓库

Create and activate virtual environment

创建并激活虚拟环境

python3 -m venv venv source venv/bin/activate # On Windows: .\venv\Scripts\activate
python3 -m venv venv source venv/bin/activate # Windows系统执行: .\venv\Scripts\activate

Install Guardian

安装Guardian

pip install -e .
undefined
pip install -e .
undefined

Verify Installation

验证安装

bash
undefined
bash
undefined

Check installation

检查安装情况

python -m cli.main --help
python -m cli.main --help

List available AI providers and models

列出可用的AI提供商和模型

python -m cli.main models
python -m cli.main models

List available workflows

列出可用的工作流

python -m cli.main workflow list
undefined
python -m cli.main workflow list
undefined

Configuration

配置

AI Provider Setup

AI提供商设置

Guardian supports four AI providers. Configure in
config/guardian.yaml
:
yaml
ai:
  # Choose: openai, claude, gemini, or openrouter
  provider: openai
  
  openai:
    model: gpt-4o
    api_key: ${OPENAI_API_KEY}
  
  claude:
    model: claude-3-5-sonnet-20241022
    api_key: ${ANTHROPIC_API_KEY}
  
  gemini:
    model: gemini-2.5-pro
    api_key: ${GOOGLE_API_KEY}
  
  openrouter:
    model: anthropic/claude-3.5-sonnet
    api_key: ${OPENROUTER_API_KEY}
  
  temperature: 0.2
  max_tokens: 8000
Guardian支持四款AI提供商,请在
config/guardian.yaml
中配置:
yaml
ai:
  # 可选值: openai, claude, gemini, or openrouter
  provider: openai
  
  openai:
    model: gpt-4o
    api_key: ${OPENAI_API_KEY}
  
  claude:
    model: claude-3-5-sonnet-20241022
    api_key: ${ANTHROPIC_API_KEY}
  
  gemini:
    model: gemini-2.5-pro
    api_key: ${GOOGLE_API_KEY}
  
  openrouter:
    model: anthropic/claude-3.5-sonnet
    api_key: ${OPENROUTER_API_KEY}
  
  temperature: 0.2
  max_tokens: 8000

Environment Variables

环境变量

bash
undefined
bash
undefined

Set API keys via environment variables

通过环境变量设置API密钥

export OPENAI_API_KEY="sk-your-key-here" export ANTHROPIC_API_KEY="sk-ant-your-key-here" export GOOGLE_API_KEY="your-gemini-key" export OPENROUTER_API_KEY="your-openrouter-key"
undefined
export OPENAI_API_KEY="sk-your-key-here" export ANTHROPIC_API_KEY="sk-ant-your-key-here" export GOOGLE_API_KEY="your-gemini-key" export OPENROUTER_API_KEY="your-openrouter-key"
undefined

Complete Configuration

完整配置

yaml
undefined
yaml
undefined

config/guardian.yaml

config/guardian.yaml

ai: provider: openai temperature: 0.2 max_tokens: 8000
pentest: safe_mode: true # Prevent destructive actions require_confirmation: true # Confirm before each step max_parallel_tools: 3 # Concurrent tool execution max_depth: 3 # Maximum scan depth tool_timeout: 300 # Timeout in seconds
output: format: markdown # markdown, html, json save_path: ./reports include_reasoning: true verbosity: normal # quiet, normal, verbose, debug
scope: blacklist: - 127.0.0.0/8 - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 require_scope_file: false max_targets: 100
tools: httpx: threads: 50 timeout: 10 tech_detect: true
nuclei: severity: ["critical", "high", "medium"] templates_path: ~/nuclei-templates
nmap: default_args: "-sV -sC" ports: "1-65535"
undefined
ai: provider: openai temperature: 0.2 max_tokens: 8000
pentest: safe_mode: true # 防止破坏性操作 require_confirmation: true # 每一步操作前需确认 max_parallel_tools: 3 # 工具并发执行数量 max_depth: 3 # 最大扫描深度 tool_timeout: 300 # 超时时间(秒)
output: format: markdown # 可选格式: markdown, html, json save_path: ./reports include_reasoning: true verbosity: normal # 日志级别: quiet, normal, verbose, debug
scope: blacklist: - 127.0.0.0/8 - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 require_scope_file: false max_targets: 100
tools: httpx: threads: 50 timeout: 10 tech_detect: true
nuclei: severity: ["critical", "high", "medium"] templates_path: ~/nuclei-templates
nmap: default_args: "-sV -sC" ports: "1-65535"
undefined

Key Commands

关键命令

Workflow Management

工作流管理

bash
undefined
bash
undefined

List all available workflows

列出所有可用工作流

python -m cli.main workflow list
python -m cli.main workflow list

Run a specific workflow

运行指定工作流

python -m cli.main workflow run --name web_pentest --target example.com
python -m cli.main workflow run --name web_pentest --target example.com

Run with specific AI provider

使用指定AI提供商运行

python -m cli.main workflow run --name web_pentest --target example.com --provider claude
python -m cli.main workflow run --name web_pentest --target example.com --provider claude

Run network assessment

运行网络评估

python -m cli.main workflow run --name network --target 192.168.1.0/24
python -m cli.main workflow run --name network --target 192.168.1.0/24

Run reconnaissance workflow

运行侦察工作流

python -m cli.main workflow run --name recon --target example.com
python -m cli.main workflow run --name recon --target example.com

Run autonomous pentest (AI-driven)

运行自主渗透测试(AI驱动)

python -m cli.main workflow run --name autonomous --target example.com
undefined
python -m cli.main workflow run --name autonomous --target example.com
undefined

Report Generation

报告生成

bash
undefined
bash
undefined

Generate markdown report

生成markdown报告

python -m cli.main report --session 20260203_175905 --format markdown
python -m cli.main report --session 20260203_175905 --format markdown

Generate HTML report with evidence

生成带证据的HTML报告

python -m cli.main report --session 20260203_175905 --format html
python -m cli.main report --session 20260203_175905 --format html

Generate JSON report

生成JSON报告

python -m cli.main report --session 20260203_175905 --format json
python -m cli.main report --session 20260203_175905 --format json

List all sessions

列出所有会话

python -m cli.main sessions list
undefined
python -m cli.main sessions list
undefined

AI Provider Commands

AI提供商命令

bash
undefined
bash
undefined

List available models

列出可用模型

python -m cli.main models
python -m cli.main models

Test AI provider connection

测试AI提供商连接

python -m cli.main test-ai --provider openai
python -m cli.main test-ai --provider openai

Switch provider for a scan

切换扫描使用的AI提供商

python -m cli.main workflow run --name web_pentest --target example.com --provider gemini
undefined
python -m cli.main workflow run --name web_pentest --target example.com --provider gemini
undefined

Custom Workflows

自定义工作流

Creating a Custom Workflow

创建自定义工作流

Create a YAML file in
workflows/custom/
:
yaml
undefined
workflows/custom/
目录下创建YAML文件:
yaml
undefined

workflows/custom/api_security.yaml

workflows/custom/api_security.yaml

name: API Security Assessment description: Comprehensive API penetration testing category: custom
parameters:

Workflow-specific parameters override config defaults

httpx: threads: 100 timeout: 15
nuclei: severity: ["critical", "high"] tags: ["api", "auth", "injection"]
steps:
  • name: API Discovery tools:
    • httpx
    • whatweb ai_instructions: | Discover all API endpoints and identify authentication mechanisms. Focus on REST, GraphQL, and SOAP endpoints.
  • name: Authentication Testing tools:
    • nuclei
    • arjun ai_instructions: | Test authentication endpoints for common vulnerabilities:
    • Broken authentication
    • JWT vulnerabilities
    • API key exposure
  • name: Input Validation tools:
    • ffuf
    • sqlmap
    • xsstrike ai_instructions: | Test input validation on all discovered parameters. Check for injection vulnerabilities and XSS.
  • name: Authorization Testing tools:
    • nuclei ai_instructions: | Test for broken object level authorization (BOLA/IDOR). Verify proper access controls on API endpoints.
reporting: include_evidence: true severity_threshold: medium format: html
undefined
name: API Security Assessment description: Comprehensive API penetration testing category: custom
parameters:

工作流特定参数会覆盖配置文件默认值

httpx: threads: 100 timeout: 15
nuclei: severity: ["critical", "high"] tags: ["api", "auth", "injection"]
steps:
  • name: API Discovery tools:
    • httpx
    • whatweb ai_instructions: | Discover all API endpoints and identify authentication mechanisms. Focus on REST, GraphQL, and SOAP endpoints.
  • name: Authentication Testing tools:
    • nuclei
    • arjun ai_instructions: | Test authentication endpoints for common vulnerabilities:
    • Broken authentication
    • JWT vulnerabilities
    • API key exposure
  • name: Input Validation tools:
    • ffuf
    • sqlmap
    • xsstrike ai_instructions: | Test input validation on all discovered parameters. Check for injection vulnerabilities and XSS.
  • name: Authorization Testing tools:
    • nuclei ai_instructions: | Test for broken object level authorization (BOLA/IDOR). Verify proper access controls on API endpoints.
reporting: include_evidence: true severity_threshold: medium format: html
undefined

Using Custom Workflows

使用自定义工作流

bash
undefined
bash
undefined

Run custom workflow

运行自定义工作流

python -m cli.main workflow run --name api_security --target https://api.example.com
python -m cli.main workflow run --name api_security --target https://api.example.com

The workflow parameters in YAML override config defaults

YAML中的工作流参数会覆盖配置文件默认值

undefined
undefined

Custom Tools Integration

自定义工具集成

Creating a Custom Tool

创建自定义工具

Create a Python file in
tools/custom/
:
python
undefined
tools/custom/
目录下创建Python文件:
python
undefined

tools/custom/custom_scanner.py

tools/custom/custom_scanner.py

from typing import Dict, Any, List from tools.base import BaseTool
class CustomScanner(BaseTool): """Custom security scanner tool."""
name = "custom_scanner"
description = "Custom security scanning tool"
category = "vulnerability"

def __init__(self):
    super().__init__()
    self.capabilities = [
        "scan_endpoint",
        "detect_vulnerabilities",
        "generate_report"
    ]

async def execute(
    self,
    target: str,
    options: Dict[str, Any] = None
) -> Dict[str, Any]:
    """
    Execute the custom scanner.
    
    Args:
        target: Target URL or IP
        options: Scanner options
    
    Returns:
        Dict containing scan results
    """
    options = options or {}
    
    # Build command
    cmd = [
        "custom-scanner",
        "--target", target
    ]
    
    if options.get("deep_scan"):
        cmd.append("--deep")
    
    if options.get("threads"):
        cmd.extend(["--threads", str(options["threads"])])
    
    # Execute tool
    result = await self._run_command(cmd)
    
    # Parse output
    findings = self._parse_output(result.get("output", ""))
    
    return {
        "success": result.get("return_code") == 0,
        "findings": findings,
        "raw_output": result.get("output"),
        "command": " ".join(cmd)
    }

def _parse_output(self, output: str) -> List[Dict[str, Any]]:
    """Parse tool output into structured findings."""
    findings = []
    
    # Custom parsing logic
    for line in output.split("\n"):
        if "VULNERABILITY" in line:
            findings.append({
                "severity": "high",
                "title": line.strip(),
                "description": "Custom vulnerability detected",
                "evidence": line
            })
    
    return findings

def validate_installation(self) -> bool:
    """Check if tool is installed."""
    return self._check_command_exists("custom-scanner")
undefined
from typing import Dict, Any, List from tools.base import BaseTool
class CustomScanner(BaseTool): """Custom security scanner tool."""
name = "custom_scanner"
description = "Custom security scanning tool"
category = "vulnerability"

def __init__(self):
    super().__init__()
    self.capabilities = [
        "scan_endpoint",
        "detect_vulnerabilities",
        "generate_report"
    ]

async def execute(
    self,
    target: str,
    options: Dict[str, Any] = None
) -> Dict[str, Any]:
    """
    Execute the custom scanner.
    
    Args:
        target: Target URL or IP
        options: Scanner options
    
    Returns:
        Dict containing scan results
    """
    options = options or {}
    
    # Build command
    cmd = [
        "custom-scanner",
        "--target", target
    ]
    
    if options.get("deep_scan"):
        cmd.append("--deep")
    
    if options.get("threads"):
        cmd.extend(["--threads", str(options["threads"])])
    
    # Execute tool
    result = await self._run_command(cmd)
    
    # Parse output
    findings = self._parse_output(result.get("output", ""))
    
    return {
        "success": result.get("return_code") == 0,
        "findings": findings,
        "raw_output": result.get("output"),
        "command": " ".join(cmd)
    }

def _parse_output(self, output: str) -> List[Dict[str, Any]]:
    """Parse tool output into structured findings."""
    findings = []
    
    # Custom parsing logic
    for line in output.split("\n"):
        if "VULNERABILITY" in line:
            findings.append({
                "severity": "high",
                "title": line.strip(),
                "description": "Custom vulnerability detected",
                "evidence": line
            })
    
    return findings

def validate_installation(self) -> bool:
    """Check if tool is installed."""
    return self._check_command_exists("custom-scanner")
undefined

Registering Custom Tools

注册自定义工具

python
undefined
python
undefined

config/custom_tools.py

config/custom_tools.py

from tools.custom.custom_scanner import CustomScanner
from tools.custom.custom_scanner import CustomScanner

Register custom tools

注册自定义工具

CUSTOM_TOOLS = { "custom_scanner": CustomScanner }
undefined
CUSTOM_TOOLS = { "custom_scanner": CustomScanner }
undefined

Common Usage Patterns

常见使用模式

Web Application Penetration Test

Web应用渗透测试

bash
undefined
bash
undefined

Quick web app security scan

快速Web应用安全扫描

python -m cli.main workflow run
--name web_pentest
--target https://testsite.example.com
--provider openai
python -m cli.main workflow run
--name web_pentest
--target https://testsite.example.com
--provider openai

This workflow includes:

该工作流包含:

- HTTP discovery (httpx)

- HTTP发现(httpx)

- Technology detection (whatweb, wafw00f)

- 技术检测(whatweb, wafw00f)

- Vulnerability scanning (nuclei, nikto)

- 漏洞扫描(nuclei, nikto)

- SQL injection testing (sqlmap)

- SQL注入测试(sqlmap)

- XSS detection (xsstrike)

- XSS检测(xsstrike)

- Directory brute forcing (gobuster)

- 目录暴力破解(gobuster)

undefined
undefined

Network Infrastructure Assessment

网络基础设施评估

bash
undefined
bash
undefined

Comprehensive network pentest

全面网络渗透测试

python -m cli.main workflow run
--name network
--target 192.168.1.0/24
--provider claude
python -m cli.main workflow run
--name network
--target 192.168.1.0/24
--provider claude

This workflow includes:

该工作流包含:

- Port scanning (nmap, masscan)

- 端口扫描(nmap, masscan)

- Service enumeration

- 服务枚举

- SSL/TLS testing (testssl, sslyze)

- SSL/TLS测试(testssl, sslyze)

- Vulnerability scanning

- 漏洞扫描

undefined
undefined

Subdomain Enumeration and Scanning

子域名枚举与扫描

bash
undefined
bash
undefined

Recon workflow for subdomain discovery

子域名发现侦察工作流

python -m cli.main workflow run
--name recon
--target example.com
--provider gemini
python -m cli.main workflow run
--name recon
--target example.com
--provider gemini

This workflow includes:

该工作流包含:

- Subdomain enumeration (subfinder, amass)

- 子域名枚举(subfinder, amass)

- DNS reconnaissance (dnsrecon)

- DNS侦察(dnsrecon)

- HTTP probing (httpx)

- HTTP探测(httpx)

- Technology fingerprinting

- 技术指纹识别

undefined
undefined

Autonomous AI-Driven Pentest

AI自主驱动渗透测试

bash
undefined
bash
undefined

Let AI decide the testing strategy

让AI决定测试策略

python -m cli.main workflow run
--name autonomous
--target example.com
--provider openai
python -m cli.main workflow run
--name autonomous
--target example.com
--provider openai

AI will:

AI将:

- Analyze the target

- 分析目标

- Select appropriate tools

- 选择合适的工具

- Adapt based on findings

- 根据发现结果调整策略

- Make strategic decisions

- 做出战略决策

undefined
undefined

Python API Usage

Python API使用

Programmatic Workflow Execution

程序化工作流执行

python
import asyncio
from guardian.core.orchestrator import Orchestrator
from guardian.core.config import Config

async def run_pentest():
    """Run programmatic penetration test."""
    
    # Load configuration
    config = Config.load("config/guardian.yaml")
    
    # Initialize orchestrator
    orchestrator = Orchestrator(config)
    
    # Define target and workflow
    target = "https://example.com"
    workflow_name = "web_pentest"
    
    # Execute workflow
    results = await orchestrator.run_workflow(
        workflow_name=workflow_name,
        target=target,
        options={
            "provider": "openai",
            "safe_mode": True,
            "max_depth": 2
        }
    )
    
    # Process results
    print(f"Scan completed: {results['session_id']}")
    print(f"Findings: {len(results['findings'])}")
    
    for finding in results['findings']:
        print(f"[{finding['severity']}] {finding['title']}")
        print(f"  Tool: {finding['tool']}")
        print(f"  Evidence: {finding['evidence'][:200]}...")
python
import asyncio
from guardian.core.orchestrator import Orchestrator
from guardian.core.config import Config

async def run_pentest():
    """Run programmatic penetration test."""
    
    # 加载配置
    config = Config.load("config/guardian.yaml")
    
    # 初始化编排器
    orchestrator = Orchestrator(config)
    
    # 定义目标和工作流
    target = "https://example.com"
    workflow_name = "web_pentest"
    
    # 执行工作流
    results = await orchestrator.run_workflow(
        workflow_name=workflow_name,
        target=target,
        options={
            "provider": "openai",
            "safe_mode": True,
            "max_depth": 2
        }
    )
    
    # 处理结果
    print(f"扫描完成: {results['session_id']}")
    print(f"发现漏洞: {len(results['findings'])}")
    
    for finding in results['findings']:
        print(f"[{finding['severity']}] {finding['title']}")
        print(f"  工具: {finding['tool']}")
        print(f"  证据: {finding['evidence'][:200]}...")

Run the pentest

运行渗透测试

asyncio.run(run_pentest())
undefined
asyncio.run(run_pentest())
undefined

Custom AI Agent Implementation

自定义AI Agent实现

python
from langchain.agents import AgentExecutor
from langchain_openai import ChatOpenAI
from guardian.agents.planner import PlannerAgent
from guardian.agents.analyzer import AnalyzerAgent

async def create_custom_agent():
    """Create custom AI agent for security analysis."""
    
    # Initialize AI model
    llm = ChatOpenAI(
        model="gpt-4o",
        temperature=0.2,
        api_key="${OPENAI_API_KEY}"
    )
    
    # Create planner agent
    planner = PlannerAgent(llm=llm)
    
    # Create analyzer agent
    analyzer = AnalyzerAgent(llm=llm)
    
    # Define target
    target = "https://example.com"
    
    # Generate test plan
    plan = await planner.create_plan(
        target=target,
        scope=["web", "api"],
        available_tools=["httpx", "nuclei", "sqlmap"]
    )
    
    print("Generated Plan:")
    for step in plan.steps:
        print(f"- {step.name}: {step.tools}")
    
    # Analyze findings
    findings = [
        {
            "severity": "high",
            "title": "SQL Injection Found",
            "tool": "sqlmap",
            "evidence": "Parameter 'id' is vulnerable"
        }
    ]
    
    analysis = await analyzer.analyze_findings(findings)
    print(f"\nAI Analysis:\n{analysis.summary}")

asyncio.run(create_custom_agent())
python
from langchain.agents import AgentExecutor
from langchain_openai import ChatOpenAI
from guardian.agents.planner import PlannerAgent
from guardian.agents.analyzer import AnalyzerAgent

async def create_custom_agent():
    """Create custom AI agent for security analysis."""
    
    # 初始化AI模型
    llm = ChatOpenAI(
        model="gpt-4o",
        temperature=0.2,
        api_key="${OPENAI_API_KEY}"
    )
    
    # 创建规划Agent
    planner = PlannerAgent(llm=llm)
    
    # 创建分析Agent
    analyzer = AnalyzerAgent(llm=llm)
    
    # 定义目标
    target = "https://example.com"
    
    # 生成测试计划
    plan = await planner.create_plan(
        target=target,
        scope=["web", "api"],
        available_tools=["httpx", "nuclei", "sqlmap"]
    )
    
    print("生成的测试计划:")
    for step in plan.steps:
        print(f"- {step.name}: {step.tools}")
    
    # 分析发现结果
    findings = [
        {
            "severity": "high",
            "title": "SQL Injection Found",
            "tool": "sqlmap",
            "evidence": "Parameter 'id' is vulnerable"
        }
    ]
    
    analysis = await analyzer.analyze_findings(findings)
    print(f"\nAI分析结果:\n{analysis.summary}")

asyncio.run(create_custom_agent())

Tool Integration Example

工具集成示例

python
from tools.registry import ToolRegistry
from guardian.core.executor import ToolExecutor

async def execute_custom_scan():
    """Execute tools programmatically."""
    
    # Get tool registry
    registry = ToolRegistry()
    
    # Get specific tool
    httpx_tool = registry.get_tool("httpx")
    
    # Execute tool
    executor = ToolExecutor(timeout=300)
    
    result = await executor.execute_tool(
        tool=httpx_tool,
        target="https://example.com",
        options={
            "threads": 50,
            "tech_detect": True,
            "status_code": True
        }
    )
    
    # Process results
    if result["success"]:
        print(f"Command: {result['command']}")
        print(f"Output:\n{result['output']}")
        
        # Extract findings
        for finding in result.get("findings", []):
            print(f"Finding: {finding['title']}")
    else:
        print(f"Error: {result.get('error')}")

asyncio.run(execute_custom_scan())
python
from tools.registry import ToolRegistry
from guardian.core.executor import ToolExecutor

async def execute_custom_scan():
    """Execute tools programmatically."""
    
    # 获取工具注册表
    registry = ToolRegistry()
    
    # 获取指定工具
    httpx_tool = registry.get_tool("httpx")
    
    # 执行工具
    executor = ToolExecutor(timeout=300)
    
    result = await executor.execute_tool(
        tool=httpx_tool,
        target="https://example.com",
        options={
            "threads": 50,
            "tech_detect": True,
            "status_code": True
        }
    )
    
    # 处理结果
    if result["success"]:
        print(f"命令: {result['command']}")
        print(f"输出:\n{result['output']}")
        
        # 提取发现结果
        for finding in result.get("findings", []):
            print(f"发现: {finding['title']}")
    else:
        print(f"错误: {result.get('error')}")

asyncio.run(execute_custom_scan())

Report Generation

报告生成

Generate Reports Programmatically

程序化生成报告

python
from guardian.reporting.generator import ReportGenerator
from guardian.core.session import SessionManager

async def generate_custom_report():
    """Generate pentest report programmatically."""
    
    # Load session
    session_mgr = SessionManager()
    session_id = "20260203_175905"
    session_data = session_mgr.load_session(session_id)
    
    # Initialize report generator
    report_gen = ReportGenerator()
    
    # Generate markdown report
    markdown_report = report_gen.generate(
        session_data=session_data,
        format="markdown",
        options={
            "include_evidence": True,
            "include_reasoning": True,
            "severity_threshold": "medium"
        }
    )
    
    # Save report
    output_path = f"reports/{session_id}_report.md"
    with open(output_path, "w") as f:
        f.write(markdown_report)
    
    print(f"Report saved to: {output_path}")
    
    # Generate HTML report
    html_report = report_gen.generate(
        session_data=session_data,
        format="html",
        options={
            "include_evidence": True,
            "template": "professional"
        }
    )
    
    # Save HTML
    html_path = f"reports/{session_id}_report.html"
    with open(html_path, "w") as f:
        f.write(html_report)
    
    print(f"HTML report saved to: {html_path}")

asyncio.run(generate_custom_report())
python
from guardian.reporting.generator import ReportGenerator
from guardian.core.session import SessionManager

async def generate_custom_report():
    """Generate pentest report programmatically."""
    
    # 加载会话
    session_mgr = SessionManager()
    session_id = "20260203_175905"
    session_data = session_mgr.load_session(session_id)
    
    # 初始化报告生成器
    report_gen = ReportGenerator()
    
    # 生成markdown报告
    markdown_report = report_gen.generate(
        session_data=session_data,
        format="markdown",
        options={
            "include_evidence": True,
            "include_reasoning": True,
            "severity_threshold": "medium"
        }
    )
    
    # 保存报告
    output_path = f"reports/{session_id}_report.md"
    with open(output_path, "w") as f:
        f.write(markdown_report)
    
    print(f"报告已保存至: {output_path}")
    
    # 生成HTML报告
    html_report = report_gen.generate(
        session_data=session_data,
        format="html",
        options={
            "include_evidence": True,
            "template": "professional"
        }
    )
    
    # 保存HTML报告
    html_path = f"reports/{session_id}_report.html"
    with open(html_path, "w") as f:
        f.write(html_report)
    
    print(f"HTML报告已保存至: {html_path}")

asyncio.run(generate_custom_report())

Troubleshooting

故障排除

AI Provider Issues

AI提供商问题

bash
undefined
bash
undefined

Problem: API key not recognized

问题: API密钥未被识别

Solution: Verify environment variable is set

解决方案: 验证环境变量是否设置正确

echo $OPENAI_API_KEY
echo $OPENAI_API_KEY

Or check config file

或检查配置文件

cat config/guardian.yaml | grep api_key
cat config/guardian.yaml | grep api_key

Test AI connection

测试AI连接

python -m cli.main test-ai --provider openai
undefined
python -m cli.main test-ai --provider openai
undefined

Tool Not Found Errors

工具未找到错误

bash
undefined
bash
undefined

Problem: "Tool not found: nmap"

问题: "Tool not found: nmap"

Solution: Install the tool

解决方案: 安装对应的工具

Check which tools are available

检查可用工具列表

python -m cli.main tools list
python -m cli.main tools list

Install missing tool

安装缺失的工具

Ubuntu/Debian

Ubuntu/Debian系统

sudo apt install nmap
sudo apt install nmap

macOS

macOS系统

brew install nmap
brew install nmap

Windows

Windows系统

choco install nmap
undefined
choco install nmap
undefined

Workflow Parameter Priority

工作流参数优先级

python
undefined
python
undefined

Parameters are applied in this order (highest to lowest):

参数优先级从高到低:

1. Workflow YAML parameters (highest priority)

1. 工作流YAML参数(最高优先级)

2. Config file parameters

2. 配置文件参数

3. Tool defaults (lowest priority)

3. 工具默认值(最低优先级)

Example: workflow overrides config

示例: 工作流参数覆盖配置文件

workflows/custom/fast_scan.yaml

workflows/custom/fast_scan.yaml

parameters: httpx: threads: 200 # Overrides config setting timeout: 5 # Overrides config setting
undefined
parameters: httpx: threads: 200 # 覆盖配置文件设置 timeout: 5 # 覆盖配置文件设置
undefined

Session and Report Issues

会话与报告问题

bash
undefined
bash
undefined

Problem: Cannot find session

问题: 无法找到会话

Solution: List all sessions

解决方案: 列出所有会话

python -m cli.main sessions list
python -m cli.main sessions list

View session details

查看会话详情

python -m cli.main sessions show --id 20260203_175905
python -m cli.main sessions show --id 20260203_175905

Clean up old sessions (older than 30 days)

清理旧会话(超过30天)

python -m cli.main sessions cleanup --days 30
undefined
python -m cli.main sessions cleanup --days 30
undefined

Permission and Scope Errors

权限与范围错误

bash
undefined
bash
undefined

Problem: "Target is blacklisted"

问题: "Target is blacklisted"

Solution: Check scope configuration in config/guardian.yaml

解决方案: 检查config/guardian.yaml中的范围配置

scope: blacklist: - 127.0.0.0/8 # localhost - 10.0.0.0/8 # private network - 172.16.0.0/12 # private network - 192.168.0.0/16 # private network

Add whitelist for internal testing

whitelist: - 192.168.1.100/32 # specific test host
undefined
scope: blacklist: - 127.0.0.0/8 # 本地主机 - 10.0.0.0/8 # 私有网络 - 172.16.0.0/12 # 私有网络 - 192.168.0.0/16 # 私有网络

为内部测试添加白名单

whitelist: - 192.168.1.100/32 # 指定测试主机
undefined

Performance Optimization

性能优化

python
undefined
python
undefined

Adjust parallel execution for faster scans

调整并行执行以加快扫描速度

pentest: max_parallel_tools: 5 # Increase from default 3 tool_timeout: 600 # Increase timeout for large targets
pentest: max_parallel_tools: 5 # 从默认3增加到5 tool_timeout: 600 # 为大型目标增加超时时间

Optimize specific tools

优化特定工具

tools: httpx: threads: 100 # Increase threads rate_limit: 150 # Requests per second
nuclei: bulk_size: 50 # Process more templates in parallel rate_limit: 150
undefined
tools: httpx: threads: 100 # 增加线程数 rate_limit: 150 # 每秒请求数
nuclei: bulk_size: 50 # 并行处理更多模板 rate_limit: 150
undefined

Debug Mode

调试模式

bash
undefined
bash
undefined

Enable verbose logging

启用详细日志

python -m cli.main workflow run
--name web_pentest
--target example.com
--verbosity debug
python -m cli.main workflow run
--name web_pentest
--target example.com
--verbosity debug

Check logs

查看日志

tail -f logs/guardian.log
tail -f logs/guardian.log

Enable AI reasoning output

启用AI推理输出

In config/guardian.yaml:

在config/guardian.yaml中:

output: include_reasoning: true # Shows AI decision-making process verbosity: debug
undefined
output: include_reasoning: true # 显示AI决策过程 verbosity: debug
undefined

Common Error Messages

常见错误信息

python
undefined
python
undefined

"Rate limit exceeded"

"Rate limit exceeded"

Solution: Add delay between requests or reduce parallelism

解决方案: 添加请求延迟或减少并行数

pentest: max_parallel_tools: 2 request_delay: 1 # seconds between requests
pentest: max_parallel_tools: 2 request_delay: 1 # 请求间隔(秒)

"Tool execution timeout"

"Tool execution timeout"

Solution: Increase timeout for specific tool

解决方案: 为特定工具增加超时时间

tools: nmap: timeout: 900 # 15 minutes for large network scans
tools: nmap: timeout: 900 # 大型网络扫描设置为15分钟

"Invalid API key"

"Invalid API key"

Solution: Regenerate API key and update environment variable

解决方案: 重新生成API密钥并更新环境变量

export OPENAI_API_KEY="sk-new-key-here"
export OPENAI_API_KEY="sk-new-key-here"

Verify with test command

使用测试命令验证

python -m cli.main test-ai --provider openai
undefined
python -m cli.main test-ai --provider openai
undefined