Join our Newsletter — 33% off our NHI Course
Home› Guides› Bandit Guide: Static Security Checks for Python Code
Guide Application Security

Bandit Guide: Static Security Checks for Python Code

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 13 min read
On this page

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 nosec with 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.

IDNameWhat it flagsSeverity / confidence
B101assert_usedassert statements, which are removed when Python runs with optimisationLow / High
B102exec_usedUse of execMedium / High
B105, B106, B107hardcoded_password_*Likely passwords in strings, function arguments and argument defaultsLow / Medium
B108hardcoded_tmp_directoryHardcoded temporary paths such as /tmpMedium / Medium
B113request_without_timeoutHTTP requests with no timeoutMedium / Low
B201flask_debug_trueFlask app run with debug=TrueHigh / Medium
B202tarfile_unsafe_memberstarfile.extractall without member filteringLow to High
B301pickleCalls that deserialise with pickleMedium (blacklist)
B307evalUse of evalMedium (blacklist)
B311randomStandard pseudo-random generators used where security may matterLow (blacklist)
B324hashlibMD4, MD5 or SHA1 used for securityMedium to High / High
B403import_pickleImport of pickle and related modulesLow (blacklist)
B501request_with_no_cert_validationverify=False on HTTP requestsHigh / High
B506yaml_loadyaml.load without a safe loaderMedium / High
B602subprocess_popen_with_shell_equals_truesubprocess calls with shell=TrueLow to High
B608hardcoded_sql_expressionsSQL built by string formattingMedium
B614pytorch_loadUnsafe loading of PyTorch model filesMedium / High
B615huggingface_unsafe_downloadHugging Face Hub downloads not pinned to an immutable commit revisionMedium / High
B701jinja2_autoescape_falseJinja2 environments with autoescape offHigh
B703django_mark_safeDjango mark_safe on untrusted contentMedium / 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/code scans recursively.
  • Show context: -n 3 prints three lines of code around each issue.
  • Pick a profile or tests: -p ShellInjection runs a named profile; -t and -s run or skip test IDs.
  • Choose an output format: -f supports csv, custom, html, json, sarif (with the extra), screen, txt, xml and yaml; -o writes to a file.
  • Exit codes: Bandit exits non-zero when it reports issues, which fails a CI step; --exit-zero forces 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.

MechanismScopeUse it forRisk if misused
skips in configWhole projectTests that do not apply, such as B101 in a project that never runs optimisedHides the test everywhere, including new code
exclude_dirsPathsGenerated code, vendored copies, virtual environmentsExcluding tests also hides secrets placed in test fixtures
# nosec B602One line, named testsA reviewed, accepted findingLow when the test ID is named
Bare # nosecOne line, all testsAvoidA new issue added to the same line later is silently ignored
Baseline (-b)Findings in a saved JSON reportAdopting Bandit on a legacy codebase so only new findings fail buildsLegacy 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_load or 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 secrets module 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

  1. Pilot in report-only mode: run with --exit-zero and JSON or SARIF output for two to four weeks to see volume and false positives.
  2. Agree the configuration: commit a pyproject.toml or .bandit file with exclusions and any skips, each with a comment explaining why.
  3. Create a baseline: generate the JSON baseline on the main branch so the gate only blocks new findings.
  4. 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.
  5. Add pre-commit: the project documents a pre-commit hook (repository https://github.com/PyCQA/bandit, hook id bandit); pin rev to a real release tag and pass args: ["-c", "pyproject.toml"] with additional_dependencies: ["bandit[toml]"] when using TOML. See the Git Hooks and Pre-commit Security Guide.
  6. Publish results: the Bandit docs give a GitHub Actions example using PyCQA/bandit-action@v1, which needs the security-events: write permission (plus actions: read and contents: read in private repositories) and accepts inputs such as configfile, severity, confidence, tests and skips. On other CI systems, upload SARIF to your code scanning dashboard. See the SARIF guide.
  7. 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

MetricWhat it showsTarget direction
Repositories with Bandit gating pull requestsCoverage of Python estateRising to all production repositories
New High confidence findings mergedGate effectivenessZero
Baseline size per repositoryLegacy debtFalling each quarter
Suppressions without a test ID or reasonSuppression hygieneZero
Median time to fix High severity findingsRemediation speedFalling
Files skipped with parse errorsBlind spots from version mismatchZero

Framework mapping

FrameworkReferenceHow Bandit contributes
NIST SP 800-53 Rev. 5SA-11(1) Static Code AnalysisAutomated static analysis of Python source
NIST SP 800-53 Rev. 5SA-11, SA-15, SI-2Developer testing, development tools and flaw remediation
NIST CSF 2.0PR.PS-06, ID.RA-01Secure development practice; identifying and recording vulnerabilities
CWEPer-issue CWE IDEach Bandit issue carries a CWE identifier for reporting

Common failure patterns

  • Blanket nosec: bare # nosec comments 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

Related NHI Mgmt Group resources: Python Security Guide · SAST Triage Guide · Software Composition Analysis (SCA) Guide · Git Hooks and Pre-commit Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.