Reputation: 191
Alright, I'm trying to write a script that will run through a generated report and give me a line count of each vulnerability type. Because of the way xml is formatted, I'm trying to use a variable to set the dictionary key when it comes across a vulnerability type, then just increment the value for that key until it reaches the end of the section.
I think I'm having an issue with how to increment the value of a key defined by a variable. This is what I've got so far.
#!/usr/bin/python
file = open('Test.xml','r')
vulns = {4:0, 3:0, 2:0, 1:0}
pos = 0
for line in file:
if line.find('Critical') != -1:
pos = 4
if line.find('High') != -1:
pos = 3
if line.find('Medium') != -1:
pos = 2
if line.find('/Chart1_CategoryGroup1_Collection') != -1:
pos = 1
if line.find('Chart1_CategoryGroup1 Label=') != -1:
vulns[pos] = vulns[pos] + 1
for i in vulns.values():
print i
When I try to run the script it kicks back
Traceback (most recent call last):
File "./vulnReport.py", line 23, in <module>
vulns[pos] = vulns[pos] + 1
KeyError: 0
Upvotes: 0
Views: 893
Reputation: 22001
You might find the following version easier to work with and maintain in the future:
#! /usr/bin/env python
import itertools
search = ('Critical',
'High',
'Medium',
'/Chart1_CategoryGroup1_Collection',
'Chart1_CategoryGroup1 Label=')
counts = dict.fromkeys(search, 0)
with open('Test.xml') as file:
for line, item in itertools.product(file, search):
counts[item] += item in line
for pair in sorted(counts.items()):
print('{!s}: {!r}'.format(*pair))
Upvotes: 0
Reputation: 8326
if line.find('Chart1_CategoryGroup1 Label=') != -1:
vulns[pos] = vulns[pos] + 1
executes before pos
gets updated to a value other than 0
, and your dict does not contain a 0
entry.
i.e., it executes
vulns[0] = vulns[0] + 1
Upvotes: 2