0
# Output Formatters
1
2
Multiple report formats for security scan results supporting different use cases, CI/CD integration, and security tool workflows. Formatters provide structured output with severity filtering, confidence thresholds, and baseline comparison capabilities.
3
4
## Capabilities
5
6
### Formatter Interface
7
8
All formatters implement a standardized interface for generating security reports from scan results.
9
10
```python { .api }
11
def report(manager, fileobj, sev_level, conf_level, lines):
12
"""
13
Generate formatted security report.
14
15
Parameters:
16
- manager: BanditManager instance containing scan results and metadata
17
- fileobj: File-like object for writing output (stdout, file handle, StringIO)
18
- sev_level: str, minimum severity level ('LOW', 'MEDIUM', 'HIGH')
19
- conf_level: str, minimum confidence level ('LOW', 'MEDIUM', 'HIGH')
20
- lines: int, maximum lines of code context (-1 for all, used to control output verbosity)
21
22
Returns:
23
None (output written to fileobj)
24
"""
25
```
26
27
### Built-in Formatters
28
29
Comprehensive set of output formats for different integration scenarios and reporting requirements.
30
31
#### JSON Formatter
32
33
```python { .api }
34
# bandit.formatters.json
35
def report(manager, fileobj, sev_level, conf_level, lines):
36
"""
37
Generate JSON format report for programmatic consumption.
38
39
Output structure:
40
{
41
"generated_at": "ISO timestamp",
42
"version": "bandit version",
43
"metrics": { "files": N, "lines": N, "issues": N },
44
"results": [
45
{
46
"filename": "path/to/file.py",
47
"test_name": "test_id",
48
"test_id": "B101",
49
"issue_severity": "HIGH",
50
"issue_confidence": "HIGH",
51
"issue_text": "Description",
52
"line_number": 42,
53
"line_range": [42, 44],
54
"col_offset": 4,
55
"code": "source code context"
56
}
57
]
58
}
59
"""
60
```
61
62
#### XML Formatter
63
64
```python { .api }
65
# bandit.formatters.xml
66
def report(manager, fileobj, sev_level, conf_level, lines):
67
"""
68
Generate XML format report for enterprise tool integration.
69
70
Output structure:
71
<testsuite name="bandit" tests="N" errors="0" failures="N" time="X">
72
<testcase classname="bandit.file_path" name="test_id" time="0">
73
<failure type="severity" message="issue_text">
74
Detailed issue information and code context
75
</failure>
76
</testcase>
77
</testsuite>
78
"""
79
```
80
81
#### HTML Formatter
82
83
```python { .api }
84
# bandit.formatters.html
85
def report(manager, fileobj, sev_level, conf_level, lines):
86
"""
87
Generate HTML report with interactive features and syntax highlighting.
88
89
Features:
90
- Responsive web interface
91
- Sortable issue tables
92
- Syntax-highlighted code context
93
- Severity-based color coding
94
- Issue filtering and search
95
- Summary statistics and charts
96
"""
97
```
98
99
#### SARIF Formatter
100
101
```python { .api }
102
# bandit.formatters.sarif
103
def report(manager, fileobj, sev_level, conf_level, lines):
104
"""
105
Generate SARIF 2.1.0 format for security tool integration.
106
107
Static Analysis Results Interchange Format for:
108
- GitHub Security tab integration
109
- Azure DevOps security scanning
110
- VS Code security extension integration
111
- Security information and event management (SIEM) tools
112
"""
113
```
114
115
#### CSV Formatter
116
117
```python { .api }
118
# bandit.formatters.csv
119
def report(manager, fileobj, sev_level, conf_level, lines):
120
"""
121
Generate CSV format for spreadsheet analysis and reporting.
122
123
Columns:
124
filename,test_name,test_id,issue_severity,issue_confidence,
125
issue_text,line_number,col_offset,code_snippet
126
"""
127
```
128
129
#### YAML Formatter
130
131
```python { .api }
132
# bandit.formatters.yaml
133
def report(manager, fileobj, sev_level, conf_level, lines):
134
"""
135
Generate YAML format for configuration-driven workflows.
136
137
Structure mirrors JSON format but with YAML syntax for:
138
- Human-readable configuration files
139
- Infrastructure as Code security scanning
140
- GitOps workflow integration
141
"""
142
```
143
144
#### Screen Formatter
145
146
```python { .api }
147
# bandit.formatters.screen
148
def report(manager, fileobj, sev_level, conf_level, lines):
149
"""
150
Generate colorized terminal output for interactive usage.
151
152
Features:
153
- ANSI color codes for severity levels
154
- Structured terminal layout
155
- Summary statistics
156
- Progress indicators
157
- Human-readable formatting
158
"""
159
```
160
161
#### Text Formatter
162
163
```python { .api }
164
# bandit.formatters.text
165
def report(manager, fileobj, sev_level, conf_level, lines):
166
"""
167
Generate plain text report for log files and simple integration.
168
169
Plain text format without colors or special formatting:
170
- Log file compatible
171
- Email reporting
172
- Simple CI/CD integration
173
- Archive-friendly format
174
"""
175
```
176
177
#### Custom Template Formatter
178
179
```python { .api }
180
# bandit.formatters.custom
181
def report(manager, fileobj, sev_level, conf_level, template=None):
182
"""
183
Generate custom format using Jinja2 templates.
184
Note: Custom formatter uses 'template' parameter instead of 'lines'.
185
186
Template variables available:
187
- results: List of filtered issues
188
- metrics: Scan statistics
189
- version: Bandit version
190
- generated_at: Timestamp
191
192
Template file specified via --msg-template option.
193
"""
194
```
195
196
## Usage Examples
197
198
### Command Line Formatter Usage
199
200
```bash
201
# JSON output to file
202
bandit -r /path/to/code -f json -o security_report.json
203
204
# HTML report with all issues
205
bandit -r /path/to/code -f html -o security_report.html
206
207
# SARIF for GitHub integration
208
bandit -r /path/to/code -f sarif -o bandit.sarif
209
210
# CSV for spreadsheet analysis
211
bandit -r /path/to/code -f csv -o issues.csv
212
213
# High-severity issues only in JSON
214
bandit -r /path/to/code -f json --severity-level high
215
```
216
217
### Programmatic Formatter Usage
218
219
```python
220
from bandit.core import manager, config
221
from bandit.formatters import json, html, sarif
222
import io
223
224
# Setup bandit manager
225
conf = config.BanditConfig()
226
b_mgr = manager.BanditManager(conf, 'file')
227
b_mgr.discover_files(['/path/to/code'], recursive=True)
228
b_mgr.run_tests()
229
230
# Generate JSON report
231
json_output = io.StringIO()
232
json.report(b_mgr, json_output, 'LOW', 'LOW', True)
233
json_data = json_output.getvalue()
234
235
# Generate HTML report
236
with open('security_report.html', 'w') as html_file:
237
html.report(b_mgr, html_file, 'MEDIUM', 'HIGH', True)
238
239
# Generate SARIF for CI/CD
240
with open('bandit.sarif', 'w') as sarif_file:
241
sarif.report(b_mgr, sarif_file, 'LOW', 'LOW', False)
242
```
243
244
### Custom Formatter Development
245
246
```python
247
from bandit.core import test_properties as test
248
249
@test.accepts_baseline()
250
def security_dashboard_formatter(manager, fileobj, sev_level, conf_level, lines):
251
"""Custom formatter for security dashboard integration."""
252
253
import json
254
from datetime import datetime
255
256
# Get filtered issues
257
issues = manager.get_issue_list(sev_level, conf_level)
258
259
# Generate dashboard-specific format
260
dashboard_data = {
261
'scan_timestamp': datetime.utcnow().isoformat(),
262
'repository': manager.config.get_option('repository_name'),
263
'summary': {
264
'total_issues': len(issues),
265
'high_severity': len([i for i in issues if i.severity == 'HIGH']),
266
'medium_severity': len([i for i in issues if i.severity == 'MEDIUM']),
267
'low_severity': len([i for i in issues if i.severity == 'LOW'])
268
},
269
'categories': {},
270
'files_affected': list(set(issue.fname for issue in issues))
271
}
272
273
# Group by CWE categories
274
for issue in issues:
275
cwe_id = str(issue.cwe.id) if issue.cwe else 'Unknown'
276
if cwe_id not in dashboard_data['categories']:
277
dashboard_data['categories'][cwe_id] = []
278
279
dashboard_data['categories'][cwe_id].append({
280
'file': issue.fname,
281
'line': issue.lineno,
282
'severity': issue.severity,
283
'confidence': issue.confidence,
284
'description': issue.text,
285
'test_id': issue.test_id
286
})
287
288
# Output JSON for dashboard consumption
289
json.dump(dashboard_data, fileobj, indent=2)
290
```
291
292
### Integration with CI/CD Pipelines
293
294
```yaml
295
# GitHub Actions example
296
- name: Run Bandit Security Scan
297
run: |
298
bandit -r src/ -f sarif -o bandit.sarif
299
bandit -r src/ -f json -o bandit.json --severity-level medium
300
301
- name: Upload SARIF to GitHub
302
uses: github/codeql-action/upload-sarif@v2
303
with:
304
sarif_file: bandit.sarif
305
306
# Jenkins pipeline example
307
stage('Security Scan') {
308
steps {
309
sh 'bandit -r src/ -f xml -o bandit.xml'
310
publishTestResults testResultsPattern: 'bandit.xml'
311
312
sh 'bandit -r src/ -f html -o security-report.html'
313
archiveArtifacts artifacts: 'security-report.html'
314
}
315
}
316
```
317
318
### Baseline Integration
319
320
```bash
321
# Generate baseline from current codebase
322
bandit-baseline -r /path/to/code -o baseline.json
323
324
# Run scan excluding baseline issues
325
bandit -r /path/to/code -b baseline.json -f json -o new-issues.json
326
327
# Compare with baseline in SARIF format
328
bandit -r /path/to/code -b baseline.json -f sarif -o delta.sarif
329
```