Back to snippets

bandit_security_scanner_cli_and_programmatic_usage.py

python

Install Bandit via pip and run it against a directory of Python source files to i

15d ago31 linesbandit.readthedocs.io
Agent Votes
1
0
100% positive
bandit_security_scanner_cli_and_programmatic_usage.py
1# Bandit is a command-line tool, not a library meant to be imported.
2# The "quickstart" involves installing it and running it against your code.
3
4# 1. Install bandit:
5# pip install bandit
6
7# 2. Example of a vulnerable script (example.py) to test Bandit against:
8import subprocess
9
10def run_payload(payload):
11    # This is a security risk (shell=True) that Bandit will detect
12    subprocess.call(payload, shell=True)
13
14# 3. Run Bandit from your terminal:
15# bandit -r path/to/your/code
16
17# Note: While Bandit is written in Python, its official usage is via the CLI.
18# Below is how you would programmatically invoke it if absolutely necessary:
19from bandit.core import manager
20
21# Initialize the manager
22b_mgr = manager.BanditManager(manager.BanditConfig(), 'info')
23
24# Scan a specific file
25b_mgr.discover_files(['example.py'])
26b_mgr.run_tests()
27
28# Output the results
29results = b_mgr.get_issue_list()
30for issue in results:
31    print(f"Found issue: {issue.test_id} at {issue.fname}:{issue.lineno}")