The Complete Production SOP: How to Deploy and Run Bandit Python AST Vulnerability Scanner in Autonomous AI Agents
Step-by-step SOP to run Bandit Python AST Vulnerability Scanner in Codex, Claude Code, and Cursor. Fix injection risks, subprocess flaws, and configure rules.
Technical Overview & Architectural Context
Autonomous coding agents frequently generate vulnerable Python code when solving operational problems. Common agent pitfalls include invoking `subprocess.Popen(..., shell=True)` for shell string formatting, introducing pickle-based deserialization for rapid caching, or falling back on pseudo-random `random` module calls instead of cryptographically sound `secrets` tokens. Furthermore, agents left without strict static analysis guardrails often fix syntax errors while completely ignoring latent Common Weakness Enumerations (CWEs) introduced by permissive string formatting in SQL statements and unsafe dynamic imports. Bandit operates at the Abstract Syntax Tree (AST) level, parsing the structural node representation of Python source files without dynamic evaluation risks. By integrating the Bandit Python AST Vulnerability Scanner skill into Codex, Claude Code, Cursor, or Windsurf, teams bind the agent to deterministic security gates. The skill provides procedural Standard Operating Procedures (SOPs) forcing agents to evaluate AST nodes, interpret issue severity and confidence ratings, and systematically refactor high-risk patterns into defense-in-depth implementations before committing workspace changes.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the Bandit Python AST Vulnerability Scanner specification into the runtime's agent skills directory.
Agent runtimes such as Claude Code, Cursor, and Codex index procedural capability manifests located in workspace or user-level configuration directories. We mount the SKILL.md into `~/.agents/skills/bandit-python-ast-security` or `.cursor/skills` so the runtime dynamically registers AST scanning triggers and bounds file writes to the current project tree.
mkdir -p ~/.agents/skills/bandit-python-ast-security && cat << 'EOF' > ~/.agents/skills/bandit-python-ast-security/SKILL.md
---
name: "bandit-python-ast-security"
description: "Scan Python codebases for common security weaknesses and injection risks with Bandit."
metadata:
author: "PyCQA"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "run bandit security scan"
- "fix bandit vulnerability python"
- "configure bandit.yaml"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: true
net_access: false
---
# Bandit Python AST Vulnerability Scanner SOP
1. Run `bandit -r src/ -f json -o bandit_report.json`.
2. Parse findings: map B602 (subprocess shell=True) to explicit array vectors without shell execution.
3. Map B311 (pseudo-random) to Python `secrets` standard library module.
4. Avoid raw SQL concatenations (B608); enforce parameterized statements via DB-API or ORM.
5. Document legitimate exceptions using `# nosec <ID>` with explicit rationale comments.
EOF---
name: "bandit-python-ast-security"
description: "Scan Python codebases for common security weaknesses and injection risks with Bandit."
metadata:
author: "PyCQA"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "run bandit security scan"
- "fix bandit vulnerability python"
- "configure bandit.yaml"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: true
net_access: false
---Direct the agent to output Bandit findings in JSON format (`-f json`) rather than plain text; JSON reduces context consumption and enables the LLM to parse structured findings deterministically.
Ensure `fs_write` is restricted to 'workspace'. Never allow global file writing permissions, which could permit automated rewriting of root-level system configurations or standard library files.
Dependency Installation & Baseline Configuration
Install Bandit within the local virtual environment and define standard baseline rules via bandit.yaml.
The agent requires the native `bandit` binary accessible in `$PATH`. We install it using `uv pip` or standard `pip`, and create a repository-level `.bandit` or `bandit.yaml` configuration to ignore non-production directories (e.g., tests, fixtures) while maintaining High/Medium strictness on core application logic.
pip install bandit[yaml] && cat << 'EOF' > .bandit
[bandit]
exclude_dirs = ['/tests', '/.venv', '/build', '/dist']
skips = ['B101']
targets = ['src']
EOFInclude `skips = ['B101']` (assert statement check) in test configuration profiles only, preventing test-suite false positives while maintaining B101 enforcement in production code.
Failing to exclude virtual environments (`.venv/` or `env/`) causes Bandit to scan hundreds of third-party dependencies, leading to agent timeouts and context token exhaustion.
Deterministic Trigger Invocation
Trigger automated security audits using precise frontmatter prompts matched against AST inspection rules.
Provide the agent with explicit natural language instructions matching the skill's trigger schema. The orchestrator routes the request to `bandit-python-ast-security`, directing the agent to execute an AST scan, parse JSON output, and systematically eliminate reported vulnerabilities.
Target specific subtrees (e.g., `run bandit security scan on src/api/routers/`) to keep prompt context windows under 2,000 tokens during remediation loops.
Agents may be tempted to suppress errors using generic `# nosec` annotations. Ensure your prompt demands actual AST refactoring rather than suppressing alerts.
Verification, AST Re-Scanning & Quality Gate
Execute an automated self-healing validation loop ensuring zero High-severity Bandit findings remain.
The skill mandates running Bandit with exit-code flags (`--exit-zero` disabled or checking `-ll -ii` for high/medium severity) as a gate before completion. This ensures that refactored code passes both standard test suites and security AST verification.
bandit -r src/ -ll -ii -f screen && pytest tests/Combine the Bandit check with `git diff --check` to verify that refactored subprocess calls did not accidentally introduce whitespace or token separation errors in argument lists.
When replacing `shell=True` with argument lists, ensure dynamic string parameters are not wrapped in quotation marks intended for shell word splitting (e.g., `['ls', '-l /tmp']` fails where `['ls', '-l', '/tmp']` succeeds).
Real-World Scenario: Remediating Subprocess Shell Injection and Insecure Random Token Generation
“Run bandit security scan on src/auth/service.py and fix all reported security vulnerabilities with safe standard library patterns.”
Runtime Troubleshooting & Failure Modes
Root Cause: The scanned Python file contains syntax incompatible with the Python runtime executing Bandit (e.g., Python 2 remnants or unparenthesized print statements under Python 3.11 AST parser).
Run `python -m py_compile src/legacy/parser.py` to isolate the syntax incompatibility, resolve the modern Python syntax error, and re-run Bandit.Root Cause: Bandit is installed within a virtualenv that is not currently activated or present in the agent runtime's default non-interactive execution PATH.
Execute Bandit via the active interpreter directly: `python -m pip install bandit && python -m bandit -r src/ -f json`Frequently Asked Questions (Bandit Python AST Vulnerability Scanner SOP)
Q:Can I use Bandit Python AST Vulnerability Scanner across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. In Cursor, place the file in `.cursor/skills/`; in Claude Code or Codex, mount it within `~/.agents/skills/bandit-python-ast-security/SKILL.md`.
Q:How does Bandit Python AST Vulnerability Scanner prevent context window overflow during long agent sessions?
By forcing the agent to output Bandit results as structured JSON and targeting specific subdirectories, the skill prevents unbounded standard output dumping into the context window.
Q:Does this skill require escalated root or container permissions?
No. The skill operates with a 98/100 security score under strict workspace boundaries (`fs_write: workspace`, `net_access: false`), performing local AST static analysis without root escalation.
Ready to equip your autonomous agent with Bandit Python AST Vulnerability Scanner?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.