Vulnerability CSV Reporting (Round 2)
CSV Schema (exact column names required)
Package,Version,CVE_ID,Severity,CVSS_Score,Fixed_Version,Title,Url
Complete, Production-Ready Script
import json, csv, sys
def get_cvss_score(vuln):
"""Extract CVSS v3 score: NVD > GHSA > RedHat > N/A"""
cvss = vuln.get('CVSS', {})
if not isinstance(cvss, dict):
return 'N/A'
for source in ['nvd', 'ghsa', 'redhat']:
entry = cvss.get(source, {})
if isinstance(entry, dict):
score = entry.get('V3Score')
if score is not None and isinstance(score, (int, float)):
return score
return 'N/A'
def generate_csv(json_input, csv_output, severities=('HIGH', 'CRITICAL')):
with open(json_input, encoding='utf-8') as f:
data = json.load(f)
records = []
seen = set() # Deduplicate by (package, version, CVE)
for result in data.get('Results', []):
for vuln in (result.get('Vulnerabilities') or []): # Handle None
severity = vuln.get('Severity', '')
if severity not in severities:
continue
key = (vuln.get('PkgName'), vuln.get('InstalledVersion'), vuln.get('VulnerabilityID'))
if key in seen:
continue
seen.add(key)
records.append({
'Package': vuln.get('PkgName') or 'N/A',
'Version': vuln.get('InstalledVersion') or 'N/A',
'CVE_ID': vuln.get('VulnerabilityID') or 'N/A',
'Severity': severity,
'CVSS_Score': get_cvss_score(vuln),
'Fixed_Version': vuln.get('FixedVersion') or 'N/A', # handles None AND ""
'Title': vuln.get('Title') or 'N/A',
'Url': vuln.get('PrimaryURL') or 'N/A',
})
headers = ['Package', 'Version', 'CVE_ID', 'Severity',
'CVSS_Score', 'Fixed_Version', 'Title', 'Url']
with open(csv_output, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=headers)
writer.writeheader()
writer.writerows(records)
print(f"[+] Wrote {len(records)} HIGH/CRITICAL records to {csv_output}")
return records
if __name__ == '__main__':
generate_csv('/root/trivy_report.json', '/root/security_audit.csv')
Key Improvements Over Round 1
- Deduplication: Use a
seen set to avoid duplicate (pkg, version, CVE) entries
- Null safety:
result.get('Vulnerabilities') or [] handles None Vulnerabilities
- Empty string fix:
vuln.get('FixedVersion') or 'N/A' catches both None and ""
- Type safety: Added
isinstance checks in CVSS extraction
- Encoding: Always use
encoding='utf-8' for both read and write
Field Mapping Reference
| CSV Column |
Trivy JSON Field |
Notes |
| Package |
PkgName |
Package name |
| Version |
InstalledVersion |
Installed version string |
| CVE_ID |
VulnerabilityID |
CVE/GHSA identifier |
| Severity |
Severity |
HIGH or CRITICAL (filtered) |
| CVSS_Score |
CVSS.{source}.V3Score |
Via priority extraction |
| Fixed_Version |
FixedVersion |
Empty/None → 'N/A' |
| Title |
Title |
Short description |
| Url |
PrimaryURL |
AVD/NVD reference link |
1---2name: run2-vulnerability-csv-reporting3description: Generate structured CSV security audit reports from Trivy JSON output with severity filtering, deduplication, and proper field mapping.4metadata:5 source: https://skillmd.com/skills/cxcscmu/run2-vulnerability-csv-reporting6---78# Vulnerability CSV Reporting (Round 2)910## CSV Schema (exact column names required)1112```13Package,Version,CVE_ID,Severity,CVSS_Score,Fixed_Version,Title,Url14```1516## Complete, Production-Ready Script1718```python19import json, csv, sys2021def get_cvss_score(vuln):22 """Extract CVSS v3 score: NVD > GHSA > RedHat > N/A"""23 cvss = vuln.get('CVSS', {})24 if not isinstance(cvss, dict):25 return 'N/A'26 for source in ['nvd', 'ghsa', 'redhat']:27 entry = cvss.get(source, {})28 if isinstance(entry, dict):29 score = entry.get('V3Score')30 if score is not None and isinstance(score, (int, float)):31 return score32 return 'N/A'3334def generate_csv(json_input, csv_output, severities=('HIGH', 'CRITICAL')):35 with open(json_input, encoding='utf-8') as f:36 data = json.load(f)3738 records = []39 seen = set() # Deduplicate by (package, version, CVE)4041 for result in data.get('Results', []):42 for vuln in (result.get('Vulnerabilities') or []): # Handle None43 severity = vuln.get('Severity', '')44 if severity not in severities:45 continue4647 key = (vuln.get('PkgName'), vuln.get('InstalledVersion'), vuln.get('VulnerabilityID'))48 if key in seen:49 continue50 seen.add(key)5152 records.append({53 'Package': vuln.get('PkgName') or 'N/A',54 'Version': vuln.get('InstalledVersion') or 'N/A',55 'CVE_ID': vuln.get('VulnerabilityID') or 'N/A',56 'Severity': severity,57 'CVSS_Score': get_cvss_score(vuln),58 'Fixed_Version': vuln.get('FixedVersion') or 'N/A', # handles None AND ""59 'Title': vuln.get('Title') or 'N/A',60 'Url': vuln.get('PrimaryURL') or 'N/A',61 })6263 headers = ['Package', 'Version', 'CVE_ID', 'Severity',64 'CVSS_Score', 'Fixed_Version', 'Title', 'Url']6566 with open(csv_output, 'w', newline='', encoding='utf-8') as f:67 writer = csv.DictWriter(f, fieldnames=headers)68 writer.writeheader()69 writer.writerows(records)7071 print(f"[+] Wrote {len(records)} HIGH/CRITICAL records to {csv_output}")72 return records7374if __name__ == '__main__':75 generate_csv('/root/trivy_report.json', '/root/security_audit.csv')76```7778## Key Improvements Over Round 179801. **Deduplication**: Use a `seen` set to avoid duplicate (pkg, version, CVE) entries812. **Null safety**: `result.get('Vulnerabilities') or []` handles `None` Vulnerabilities823. **Empty string fix**: `vuln.get('FixedVersion') or 'N/A'` catches both `None` and `""`834. **Type safety**: Added `isinstance` checks in CVSS extraction845. **Encoding**: Always use `encoding='utf-8'` for both read and write8586## Field Mapping Reference8788| CSV Column | Trivy JSON Field | Notes |89|------------|-----------------|-------|90| Package | `PkgName` | Package name |91| Version | `InstalledVersion` | Installed version string |92| CVE_ID | `VulnerabilityID` | CVE/GHSA identifier |93| Severity | `Severity` | HIGH or CRITICAL (filtered) |94| CVSS_Score | `CVSS.{source}.V3Score` | Via priority extraction |95| Fixed_Version | `FixedVersion` | Empty/None → 'N/A' |96| Title | `Title` | Short description |97| Url | `PrimaryURL` | AVD/NVD reference link |