Find Security Issues in Python Code with Bandit
Scan Python projects with Bandit, review common security findings, configure checks safely, and add a reliable CI gate.
Overview
Bandit is a static analysis tool that scans Python code for common security vulnerabilities. It parses the AST (Abstract Syntax Tree) and checks for known insecure patterns — hardcoded passwords, shell injection, weak crypto, assert statements in production, and more. Bandit produces a report with severity levels (LOW, MEDIUM, HIGH) and confidence levels (LOW, MEDIUM, HIGH) for each finding.
When to Use
- Scanning Python projects for common security issues before release
- Integrating security checks into CI/CD pipelines
- Auditing third-party Python code or dependencies
- Enforcing security standards across a team
- Pre-commit hooks to catch issues before they reach the repository
When NOT to Use
- Non-Python codebases — Bandit only supports Python
- Runtime vulnerability detection — Bandit is static analysis only
- Dependency vulnerability scanning — use
pip-auditorsafetyinstead - When you need deep taint analysis — Bandit checks patterns, not data flow
Solution
Install Bandit
pip install bandit
# Or as a dev dependency
pip install "bandit[toml]"
# Using poetry
poetry add --group dev "bandit[toml]"
# Using pipenv
pipenv install --dev "bandit[toml]"
Basic scan
# Scan a single file
bandit myapp.py
# Scan a directory recursively
bandit -r src/
# Scan with verbose output
bandit -r src/ -v
# Output to a file
bandit -r src/ -o bandit-report.txt
# JSON output for CI/CD
bandit -r src/ -f json -o bandit-report.json
# HTML report
bandit -r src/ -f html -o bandit-report.html
Understand the output
Each finding includes a test ID, the source location, a short message, severity, and confidence. Start with the ID and read the rule description before changing code. Severity describes the potential impact; confidence describes how strongly the syntax matches the rule. A high-confidence result can still be a false positive, and a low-confidence result still deserves review when the code handles secrets, subprocesses, deserialization, or network requests.
Bandit builds an abstract syntax tree and applies checks to syntax patterns. It doesn’t run the program or trace values through the whole application, so a clean scan only means the enabled checks found no matching patterns in the scanned files — it isn’t proof the code is secure. Define the scan boundary explicitly and pair it with dependency auditing, tests, code review, and runtime controls appropriate to the application.
The default run turns on the available checks. Narrowing the test set or suppressing a check reduces what the report can find. When a team hits a false positive, document the specific rule, affected line, and reason instead of excluding a broad category. Revisit exceptions when the code or the Bandit version changes.
Configuration file
# .bandit — Bandit configuration
[bandit]
# Exclude generated or vendored directories; keep Bandit's default checks enabled.
exclude = venv,.venv,__pycache__,build,dist
Bandit reads a project-root .bandit INI file when invoked recursively, for example with bandit -r src/. The exclude option is for INI files; don’t put exclude_dirs in this file. Avoid a skips list as a starter configuration: it can hide real findings, especially when it disables password, network-binding, or subprocess checks. Exclude only directories that shouldn’t be scanned, such as virtual environments or generated output. If tests are in scope, don’t exclude them just to make the report quieter.
TOML configuration in pyproject.toml
# pyproject.toml
[tool.bandit]
exclude_dirs = ["venv", ".venv", "__pycache__", "build", "dist"]
Load TOML configuration explicitly and install the optional TOML support:
python -m pip install "bandit[toml]"
bandit -c pyproject.toml -r src/
Keep settings under [tool.bandit]. If you define tests, Bandit runs only that allowlist; it isn’t an extra list added on top of the defaults. Use a reduced test set only when the project has a documented reason and review the omitted checks periodically.
Common Bandit findings and fixes
B101: Assert statements in production
# BAD — Bandit B101
assert user.is_authenticated, "User not authenticated"
# GOOD — raise explicit exception
if not user.is_authenticated:
raise PermissionError("User not authenticated")
B105: Hardcoded password string
# BAD — Bandit B105
PASSWORD = "admin123"
API_KEY = "sk-abc123"
# GOOD — use environment variables
import os
PASSWORD = os.environ["APP_PASSWORD"]
API_KEY = os.environ["API_KEY"]
B602/B603: Subprocess shell injection
# BAD — Bandit B602 (shell=True)
import subprocess
subprocess.call(f"ls {user_input}", shell=True)
# GOOD — pass args as list, no shell
import subprocess
subprocess.call(["ls", user_input])
# GOOD — keep arguments separate and stop option parsing before user values
subprocess.run(["grep", "-F", "--", pattern, filename], check=True)
shlex.split() only tokenizes a string; it doesn’t validate values or prevent argument injection. Prefer a fixed argument list, validate paths against the application’s policy, and keep shell=False.
B301: Pickle deserialization
# BAD — Bandit B301
import pickle
data = pickle.loads(user_supplied_bytes)
# Safer for data interchange, then validate the parsed structure
import json
data = json.loads(user_supplied_string)
JSON parsing doesn’t execute Python object constructors as pickle can, but its output is still untrusted input. Set size limits and validate expected keys, types, and values before using it.
B302: marshal deserialization
# BAD — Bandit B302; do not load untrusted bytes with marshal
import marshal
value = marshal.loads(untrusted_bytes)
marshal is an internal serialization format, not a safe interchange format for user-controlled data. Don’t suppress B302 just because the bytes come from a file; verify who can write that file and choose a format with explicit validation.
B501: Request with verify=False
# BAD — Bandit B501 (SSL verification disabled)
import requests
response = requests.get(url, verify=False)
# GOOD — always verify SSL
import requests
response = requests.get(url, verify=True)
B311: Random for crypto
# BAD — Bandit B311 (random is not cryptographically secure)
import random
token = ''.join(random.choices(string.ascii_letters, k=32))
# GOOD — use secrets module
import secrets
token = ''.join(secrets.choice(string.ascii_letters) for _ in range(32))
# Or simpler:
token = secrets.token_urlsafe(32)
B404: Importing subprocess
# Bandit B404 flags the import; review the calls separately.
import subprocess
# Bandit may also flag the call as B603, even with shell=False.
subprocess.run(["git", "status", "--short"], check=True)
Inline suppressions
# Suppress a specific finding on a line
password = "test-password" # nosec B105 — test fixture, not production
# B603 applies to the call, so put its suppression on that line.
import subprocess
subprocess.run(["git", "status"], check=True) # nosec B603 — fixed, reviewed arguments
# Do not suppress every rule on a line when one test ID is sufficient.
Bandit reads # nosec on the source line that produced the finding. A comment on the preceding line or on an import doesn’t suppress a later call. Prefer a specific test ID, and explain the verified reason beside it. Suppressions are exceptions, not substitutes for input validation or a safer API; review them during code review and remove them when the underlying code changes.
CI/CD integration with GitHub Actions
# .github/workflows/bandit.yml
name: Bandit Security Scan
on: [push, pull_request]
jobs:
bandit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Bandit
run: pip install bandit[toml]
- name: Run Bandit
run: bandit -r src/ --severity-level high -f json -o bandit-report.json
- name: Upload report
if: always()
uses: actions/upload-artifact@v4
with:
name: bandit-report
path: bandit-report.json
Pre-commit hook
# .pre-commit-config.yaml
repos:
- repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
- id: bandit
args: ["--severity-level", "medium"]
exclude: ^(tests/|migrations/)
The pre-commit hook receives changed files from pre-commit, so it doesn’t need -r src/. This keeps local checks focused; CI still scans the complete source tree. Pin the hook to a release and update it deliberately rather than copying an old tag.
Baseline file for incremental scanning
# Review current findings, then record the accepted starting point.
bandit -r src/ -f json -o .bandit-baseline.json --exit-zero
# Report findings that are not in the reviewed baseline.
bandit -r src/ -b .bandit-baseline.json
Don’t create a baseline merely to make CI green. First triage the report, fix urgent issues, and record why any accepted legacy result remains. Store the baseline under version control so reviewers can see changes to it. When a finding is fixed, remove its entry through the normal baseline update process; otherwise the file can conceal regressions or make old results look permanently accepted.
Custom Bandit plugin
# bandit_plugins/no_print_statements.py
import bandit
from bandit.core import test_properties
@test_properties.checks("Call")
def no_print_statements(context):
if context.call_function_name == "print":
return bandit.Issue(
severity=bandit.MEDIUM,
confidence=bandit.HIGH,
text="Print used; review whether a logger is more appropriate.",
lineno=context.node.lineno,
)
# Add to the installed project's pyproject.toml.
[project.entry-points."bandit.plugins"]
no_print_statements = "bandit_plugins.no_print_statements:no_print_statements"
Bandit discovers custom tests through the bandit.plugins entry-point group. The module must be importable from the environment where Bandit runs, so package the plugin and install the project before scanning. The entry point registers the function; a file path passed as --plugins isn’t a supported Bandit CLI option. Keep custom rules narrow and add tests for both matching and non-matching code before relying on them in CI.
Variants
Bandit with tox
# tox.ini
[tox]
envlist = bandit
[testenv:bandit]
deps = bandit
commands = bandit -r src/ -ll -ii
Bandit in Makefile
# Makefile
.PHONY: security
security:
bandit -r src/ -ll -ii -f json -o bandit-report.json
@echo "Bandit scan complete. Report: bandit-report.json"
.PHONY: security-verbose
security-verbose:
bandit -r src/ -v
Bandit with severity filtering
# Only show MEDIUM and HIGH severity (-ll)
bandit -r src/ -ll
# Only show HIGH severity (-lll)
bandit -r src/ -lll
# Only show HIGH confidence findings (-ii)
bandit -r src/ -ii
# Equivalent explicit form with the long options
bandit -r src/ --severity-level high --confidence-level medium
Repeating -l or -i raises the threshold: -l, -ll, and -lll map to severity LOW, MEDIUM, and HIGH, and -i works the same way for confidence. The long forms --severity-level and --confidence-level say the same thing more readably in scripts and CI. Filtering only changes the report; the checks still run, so the failure criterion matches what you see in the output and a reviewer can tell why a change broke the gate.
Best Practices
- Run Bandit in CI/CD to catch security issues before merge.
- Filter by severity in CI, but review LOW findings periodically: some flag patterns that escalate later.
- Keep the configuration in the repository and document the reason for every exclusion or suppression.
- Use a baseline only on legacy codebases, after triaging the existing results.
- Combine with
pip-audit— Bandit reviews your code, pip-audit reviews installed dependencies. - Run the pre-commit hook on changed files and leave the full-tree scan to CI.
- Recheck skips and suppressions when upgrading Bandit; releases can change or add rules.
Common Mistakes
- Suppressing findings without review:
# nosecwith no explanation hides real vulnerabilities. Always write down the reason. - Shipping
skipsas a starter config: disabling B105, B104, or the subprocess checks turns off exactly the findings Bandit is best at catching. - Masking CI with
|| trueand re-parsing the JSON: Bandit already reflects the result in its exit code at the chosen threshold; a manual parser adds fragility. - Putting
# nosecon the wrong line: it only applies to the line it sits on; a comment on the import doesn’t cover the call that triggered the finding. - Treating a clean scan as proof of safety: Bandit matches syntax patterns, not business-logic flaws or issues that only appear at runtime.
Further Reading
- Bandit documentation — configuration: INI and TOML options,
excludevsexclude_dirs, and howtests/skipsbehave. - Bandit test plugin index: the official list of check IDs (B101–B704) and what each rule detects.
- Extending Bandit with plugins: entry-point registration for custom checks.
- Companion configuration files: the
.bandit, TOML, pre-commit, CI workflow, and plugin files from this recipe, ready to copy.
Frequently Asked Questions
What is Bandit?
A static analysis tool for Python that scans code for common security vulnerabilities by parsing the AST and checking for known insecure patterns.
How does Bandit differ from pip-audit?
Bandit scans your source code for insecure coding patterns; pip-audit compares installed dependencies against vulnerability databases. They complement each other — one covers your own code, the other covers third-party libraries. For dependency scanning, see Find Vulnerabilities in Python Dependencies with pip-audit.
What do severity and confidence mean in Bandit?
Severity (LOW/MEDIUM/HIGH) indicates the potential impact of the vulnerability. Confidence (LOW/MEDIUM/HIGH) indicates how certain Bandit is that the finding is real. Filter by both to reduce false positives.
How do I suppress a Bandit finding?
Add # nosec with the specific test ID at the end of the line that produced the finding — for example # nosec B602 — plus a comment with the verified reason. Bare # nosec suppresses every rule on that line, so use it only when there's no alternative.
Can Bandit detect all security vulnerabilities?
No. It only finds the patterns its rules know about in the files it scans. It doesn't detect business-logic flaws, environment misconfiguration, or issues that depend on runtime behavior. Treat it as one layer inside a broader review, like the one in Security Review Checklist for Pull Requests.
Related Resources
Scan Python Packages for Known CVEs with pip-audit
How to use pip-audit to scan Python dependencies for known vulnerabilities, configure ignore lists, integrate with CI/CD, and remediate findings.
RecipeStrict Type Checking in Python with mypy
How to configure mypy strict mode for Python projects, handle common type errors, use Protocol and TypeGuard, and integrate with CI/CD.
RecipeShare Workflow Logic with GitHub Actions Reusable Workflows
How to create and consume reusable workflows in GitHub Actions, covering inputs, secrets, conditional jobs, matrix strategy, and organization-wide sharing.
RecipeDetect Bugs in Java with SpotBugs Static Analysis
How to configure SpotBugs for Maven and Gradle, interpret bug patterns, suppress false positives, and integrate with CI/CD pipelines.
RecipeEnforce Security Rules in Node.js with ESLint
How to configure eslint-plugin-security to detect insecure patterns in Node.js code, handle false positives, and integrate with CI/CD pipelines.
GuideSecure Coding Practices — By Language and Pattern
A practical guide to secure coding practices across languages: input validation, memory safety, authentication, and defensive patterns for Python, Java, JavaScript, and Go.