Python code reaches production with shell calls, unsafe deserialisation and hardcoded credentials that a fast static check would have caught at commit time. Bandit is an open source tool from the Python Code Quality Authority (PyCQA) that parses each Python file into an abstract syntax tree (AST) and runs security plugins against it. This guide explains what Bandit checks, how its test IDs and its severity and confidence ratings work, how to configure it, how to use baselines and nosec without hiding real issues, how to run it in CI and pre-commit, and how to pair it with dependency scanning. It is written for Python developers and application security engineers and reflects Bandit 1.9.4, the latest release tag in November 2026.
This is an independent guide from NHI Mgmt Group, based on Bandit's public documentation as of November 2026. It is not sponsored or reviewed by the Bandit project. Product features change, so confirm settings against Bandit's current documentation.
Key takeaways
- Bandit reads code, it does not run it. It builds an AST per file and matches plugins against calls, imports and strings, so it is fast enough for every commit.
- Every finding has two ratings. Severity says how bad the issue would be; confidence says how sure Bandit is. Gate builds on high confidence first.
- Test IDs are grouped by theme. B1xx are general issues, B2xx application or framework misconfiguration, B3xx blacklisted calls, B4xx blacklisted imports, B5xx cryptography, B6xx injection and B7xx cross-site scripting.
- Suppress narrowly. Use
nosecwith a specific test ID and a reason, and use a JSON baseline to separate legacy findings from new ones. - Pair it with dependency scanning. Bandit checks your own code; known vulnerabilities in third-party packages need software composition analysis alongside it.
What Bandit checks
Bandit's README describes it as a tool to find common security issues in Python code: it processes each file, builds an AST and runs the relevant plugins against the AST nodes. Plugins come in two forms. Test plugins inspect patterns (for example a subprocess call with shell=True). Blacklist checks flag calls (B3xx) or imports (B4xx) of functions and modules that are risky by nature, such as pickle or telnetlib. Each issue carries a CWE identifier, which helps map findings to your vulnerability taxonomy. Bandit began in the OpenStack Security Project and is released under the Apache License 2.0.
Common test IDs
The table lists the tests most teams meet first, with the severity and confidence set in the plugin source for Bandit 1.9.4. Where a test can raise several levels depending on context, the range is shown. Test IDs and ratings change between releases, so check the plugin list for your version.
| ID | Name | What it flags | Severity / confidence |
|---|---|---|---|
| B101 | assert_used | assert statements, which are removed when Python runs with optimisation | Low / High |
| B102 | exec_used | Use of exec | Medium / High |
| B105, B106, B107 | hardcoded_password_* | Likely passwords in strings, function arguments and argument defaults | Low / Medium |
| B108 | hardcoded_tmp_directory | Hardcoded temporary paths such as /tmp | Medium / Medium |
| B113 | request_without_timeout | HTTP requests with no timeout | Medium / Low |
| B201 | flask_debug_true | Flask app run with debug=True | High / Medium |
| B202 | tarfile_unsafe_members | tarfile.extractall without member filtering | Low to High |
| B301 | pickle | Calls that deserialise with pickle | Medium (blacklist) |
| B307 | eval | Use of eval | Medium (blacklist) |
| B311 | random | Standard pseudo-random generators used where security may matter | Low (blacklist) |
| B324 | hashlib | MD4, MD5 or SHA1 used for security | Medium to High / High |
| B403 | import_pickle | Import of pickle and related modules | Low (blacklist) |
| B501 | request_with_no_cert_validation | verify=False on HTTP requests | High / High |
| B506 | yaml_load | yaml.load without a safe loader | Medium / High |
| B602 | subprocess_popen_with_shell_equals_true | subprocess calls with shell=True | Low to High |
| B608 | hardcoded_sql_expressions | SQL built by string formatting | Medium |
| B614 | pytorch_load | Unsafe loading of PyTorch model files | Medium / High |
| B615 | huggingface_unsafe_download | Hugging Face Hub downloads not pinned to an immutable commit revision | Medium / High |
| B701 | jinja2_autoescape_false | Jinja2 environments with autoescape off | High |
| B703 | django_mark_safe | Django mark_safe on untrusted content | Medium / High |
Some IDs are retired and kept in the docs for history only, for example B309 (httpsconnection), B320, B322 (input), B325 (tempnam), B410 (import_lxml) and B414 (import_pycryptodome). A configuration that lists them does nothing. B614 and B615 matter for teams shipping machine learning code: see the Python Security Guide for the safe alternatives to pickle-based formats.
Severity and confidence
Severity (Low, Medium, High) is the plugin author's view of impact if the finding is real. Confidence (Low, Medium, High) is how likely it is that the pattern is a real issue rather than a coincidence. B105 hardcoded password strings, for example, are Low severity and Medium confidence because many matches are test values or field names. B501 disabled certificate verification is High on both. Filter on the command line with -l, -ll or -lll (or --severity-level low|medium|high) and -i, -ii or -iii (or --confidence-level). The CLI help notes that all and low usually give the same results, but rules with no defined level appear only under all.
Installing and running Bandit
Bandit is distributed on PyPI and installs with pip, ideally in a virtual environment or as a pinned development dependency. Optional extras add features: bandit[toml] for pyproject.toml configuration, bandit[baseline] for the bandit-baseline command and bandit[sarif] for SARIF output. The project also publishes a container image built in the repository.
- Scan a tree:
bandit -r path/to/codescans recursively. - Show context:
-n 3prints three lines of code around each issue. - Pick a profile or tests:
-p ShellInjectionruns a named profile;-tand-srun or skip test IDs. - Choose an output format:
-fsupports csv, custom, html, json, sarif (with the extra), screen, txt, xml and yaml;-owrites to a file. - Exit codes: Bandit exits non-zero when it reports issues, which fails a CI step;
--exit-zeroforces success for report-only runs.
Python version: the Bandit FAQ explains that Bandit uses the standard library ast module, which only parses code valid for the interpreter it runs under. Run Bandit on the same Python version your project targets, or syntax errors will hide files from the scan. See Python End of Life Versions for supported versions.
Configuration and baselines
Bandit reads an INI file named .bandit in the project directory when run with -r. YAML and TOML files are also supported but must be passed with -c (for example bandit -c pyproject.toml -r . with settings under [tool.bandit]). Supported keys are targets, exclude (INI) or exclude_dirs (YAML and TOML), tests and skips. A YAML or TOML file can also override plugin settings, such as which functions any_other_function_with_shell_equals_true treats as shell, no-shell or subprocess calls. bandit-config-generator produces a template with every plugin's defaults.
| Mechanism | Scope | Use it for | Risk if misused |
|---|---|---|---|
skips in config | Whole project | Tests that do not apply, such as B101 in a project that never runs optimised | Hides the test everywhere, including new code |
exclude_dirs | Paths | Generated code, vendored copies, virtual environments | Excluding tests also hides secrets placed in test fixtures |
# nosec B602 | One line, named tests | A reviewed, accepted finding | Low when the test ID is named |
Bare # nosec | One line, all tests | Avoid | A new issue added to the same line later is silently ignored |
Baseline (-b) | Findings in a saved JSON report | Adopting Bandit on a legacy codebase so only new findings fail builds | Legacy findings are forgotten unless tracked |
The configuration docs explain why to name tests in nosec: several issues can share a line, and a specific suppression keeps reporting the others. Full test names work too (# nosec assert_used). Add a short reason after the suppression and review suppressions in code review; --ignore-nosec runs a scan that disregards them all, which is useful for a periodic audit. A baseline is a JSON report created with -f json -o; later runs with -b report only findings not in it. Commit the baseline, treat changes to it as security-relevant in review, and keep a ticket to burn down the legacy findings. The SAST Triage Guide covers baseline and suppression governance in depth.
Triage of common findings
- B602, B603, B604, B605, B607 (process execution): confirm whether any part of the command comes from user input, files or the network. Pass an argument list with
shell=False, use full executable paths to clear B607, and never build a shell string from untrusted data. B603 (subprocess without shell) is informational in most code and often skipped for trusted internal commands. - B301, B403, B614 (deserialisation): treat as real when the data can come from outside the process, including model files and caches. Replace with JSON or another data-only format, or load model weights with safe options.
- B506 (yaml.load): switch to
yaml.safe_loador pass a safe loader. This is almost always a quick, correct fix. - B105 to B107 (hardcoded passwords): many hits are variable names such as
password_field. Real credentials must be revoked and rotated, not only removed from code, and moved to a secrets manager. See the Developer Secret Scanning Triage guide. - B501 (verify=False) and B113 (no timeout): fix by default. Point to a corporate CA bundle instead of disabling verification, and set explicit timeouts.
- B608 (SQL strings): check whether values reach the query unparameterised; use parameterised queries or the ORM's query builder.
- B311 (random): real only where the value is a token, password or key; use the
secretsmodule there. - B101 (assert): real when an assert enforces a security check, because optimised runs strip it. Common practice is to skip B101 for test directories only.
Where identity fits
Hardcoded secrets are machine credentials: API keys, database passwords and service tokens in Python scripts often have broad, long-lived access. A Bandit B105 to B107 finding is a prompt to check whether the value was ever committed, rotate it, and move the workload to a short-lived credential. See the Git Secret Scanning Guide for scanning history, which Bandit does not inspect.
Bandit in CI and pre-commit
- Pilot in report-only mode: run with
--exit-zeroand JSON or SARIF output for two to four weeks to see volume and false positives. - Agree the configuration: commit a
pyproject.tomlor.banditfile with exclusions and any skips, each with a comment explaining why. - Create a baseline: generate the JSON baseline on the main branch so the gate only blocks new findings.
- Gate on high confidence: fail pull requests on High confidence findings of Medium severity and above, for example
-ll -iii; widen the gate as the backlog falls. - Add pre-commit: the project documents a pre-commit hook (repository
https://github.com/PyCQA/bandit, hook idbandit); pinrevto a real release tag and passargs: ["-c", "pyproject.toml"]withadditional_dependencies: ["bandit[toml]"]when using TOML. See the Git Hooks and Pre-commit Security Guide. - Publish results: the Bandit docs give a GitHub Actions example using
PyCQA/bandit-action@v1, which needs thesecurity-events: writepermission (plusactions: readandcontents: readin private repositories) and accepts inputs such asconfigfile,severity,confidence,testsandskips. On other CI systems, upload SARIF to your code scanning dashboard. See the SARIF guide. - Roll back safely: if a new Bandit release adds noisy findings, pin the previous version in your lock file, open a ticket, and update the configuration before unpinning.
Small versus large teams: a small team can run Bandit in pre-commit and CI with the default tests and a few skips. A larger organisation should publish a shared configuration, collect SARIF centrally, and track suppressions and baseline size per repository. The SAST, SCA and code scanning tool rollout playbook covers the programme side.
Pairing with dependency scanning
Bandit inspects first-party source. It does not check whether a pinned version of requests or PyYAML has a published vulnerability, or whether a package was malicious. Run software composition analysis against the lock file in the same pipeline, with hashed lockfiles and a vetted package index. See the Software Composition Analysis (SCA) Guide, SAST vs SCA and the Python Packaging and pip Security Guide.
Limits of Bandit
Bandit is designed as a fast, per-file pattern checker, and knowing its scope helps you place it correctly.
- Per-file analysis: it matches patterns in each file's AST, so it does not follow tainted data from a web request through several modules to a sink. Use code review and deeper data-flow analysis for those paths.
- Logic and access control: broken authorisation, insecure direct object references and business logic flaws are outside a pattern checker's view; use threat modelling, tests and the Secure Code Review Checklist.
- Runtime configuration: settings loaded from environment variables or files at runtime are not visible.
- Repository history: it scans the current tree; secrets removed from code may still sit in Git history.
- Version coupling: it parses code with the interpreter it runs under, so mismatched versions skip files with syntax errors. Watch for parse errors in the output.
Detection and measurement
| Metric | What it shows | Target direction |
|---|---|---|
| Repositories with Bandit gating pull requests | Coverage of Python estate | Rising to all production repositories |
| New High confidence findings merged | Gate effectiveness | Zero |
| Baseline size per repository | Legacy debt | Falling each quarter |
| Suppressions without a test ID or reason | Suppression hygiene | Zero |
| Median time to fix High severity findings | Remediation speed | Falling |
| Files skipped with parse errors | Blind spots from version mismatch | Zero |
Framework mapping
| Framework | Reference | How Bandit contributes |
|---|---|---|
| NIST SP 800-53 Rev. 5 | SA-11(1) Static Code Analysis | Automated static analysis of Python source |
| NIST SP 800-53 Rev. 5 | SA-11, SA-15, SI-2 | Developer testing, development tools and flaw remediation |
| NIST CSF 2.0 | PR.PS-06, ID.RA-01 | Secure development practice; identifying and recording vulnerabilities |
| CWE | Per-issue CWE ID | Each Bandit issue carries a CWE identifier for reporting |
Common failure patterns
- Blanket nosec: bare
# noseccomments accumulate and hide later issues on the same lines. - Excluding tests wholesale: test fixtures hold real tokens more often than teams expect.
- Gating on everything at once: failing builds on all Low confidence findings on day one leads teams to disable the tool.
- Unpinned Bandit: a new release changes results overnight and breaks pipelines; pin it and update deliberately.
- Removing a secret without rotating it: the value lives on in history and forks.
- Treating Bandit as the whole programme: no dependency scanning, no review of logic flaws.
Practitioner checklist
- Pin Bandit as a development dependency and run it on your target Python version.
- Commit a configuration file with exclusions and skips, each with a written reason.
- Create a JSON baseline for legacy code and schedule its burn-down.
- Require test IDs and a reason on every
nosec; audit periodically with--ignore-nosec. - Add the pre-commit hook pinned to a release tag.
- Gate pull requests on High confidence, Medium and above findings, then widen.
- Publish SARIF to your code scanning dashboard.
- Rotate any real credential Bandit finds, then move it to a secrets manager.
- Run software composition analysis on the lock file in the same pipeline.
Standards and references
- Bandit: Documentation
- Bandit: Test Plugins
- Bandit: Configuration
- Bandit: GitHub Actions Workflow
- PyCQA: Bandit repository
- NIST: SP 800-53 Rev. 5
- Bandit: Getting Started
Related NHI Mgmt Group resources: Python Security Guide · SAST Triage Guide · Software Composition Analysis (SCA) Guide · Git Hooks and Pre-commit Security Guide