Verified SOP & TutorialAudited Score 98/100

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.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

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

Codex CLI/Desktop, Claude Code CLI, Cursor, or Windsurf installed with active workspace
Python 3.10+ and pip/uv installed in the local environment
Git 2.40+ initialized with clean tracking branch

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install bandit-python-ast-security in cursor ide#claude code bandit-python-ast-security rules#codex desktop bandit-python-ast-security setup tutorial#how to fix bandit-python-ast-security agent execution error#python ast vulnerability scanner claude code skill#bandit security scan windsurf agent prompt#bandit-python-ast-security sandbox permissions and security score#remediate bandit python security warnings in cursor

Step-by-Step Execution Playbook

1

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.

Terminal Command
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
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
---
Production Pro-Tip

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.

Sandbox Gotcha

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.

2

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.

Terminal Command
pip install bandit[yaml] && cat << 'EOF' > .bandit [bandit] exclude_dirs = ['/tests', '/.venv', '/build', '/dist'] skips = ['B101'] targets = ['src'] EOF
Production Pro-Tip

Include `skips = ['B101']` (assert statement check) in test configuration profiles only, preventing test-suite false positives while maintaining B101 enforcement in production code.

Sandbox Gotcha

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.

3

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.

Production Pro-Tip

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.

Sandbox Gotcha

Agents may be tempted to suppress errors using generic `# nosec` annotations. Ensure your prompt demands actual AST refactoring rather than suppressing alerts.

4

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.

Terminal Command
bandit -r src/ -ll -ii -f screen && pytest tests/
Production Pro-Tip

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.

Sandbox Gotcha

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

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“Run bandit security scan on src/auth/service.py and fix all reported security vulnerabilities with safe standard library patterns.”

Deterministic Agent Verification Pipeline:
Agent invokes `bandit -r src/auth/service.py -f json` and identifies B602 (subprocess with shell=True) on line 42 and B311 (insecure pseudo-random generator) on line 87.
Agent refactors `subprocess.Popen(f'echo {user_input}', shell=True)` to `subprocess.run(['echo', user_input], check=True, capture_output=True, text=True)`.
Agent replaces `import random` with `import secrets` and refactors `token = ''.join(random.choices(...))` to `secrets.token_urlsafe(32)`.
Agent re-executes `bandit -r src/auth/service.py -ll` to confirm that all Medium and High vulnerabilities are cleared with return code 0.

Runtime Troubleshooting & Failure Modes

Error: [main] ERROR: Bandit could not parse file: src/legacy/parser.py: SyntaxError: invalid syntax

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).

Resolution Command / Fix:
Run `python -m py_compile src/legacy/parser.py` to isolate the syntax incompatibility, resolve the modern Python syntax error, and re-run Bandit.
Error: bandit: command not found (or return code 127 in agent sandbox)

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.

Resolution Command / Fix:
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.

Get 1-Click Install Spec