I have spent more time on this issue than I'd care to admit. The below code is working pulling data from XML using elementtree. I am then writing it to a Sqlite DB.
The problem I am getting is that my hosts table is creating multiple entries for the same host and I cant work out why. When printing the data (as in the code) the data seems to print correctly, so its baffling me.
Example of Data Output In DB
Code
#!/usr/local/bin/python
import elementtree.ElementTree as ET
import sqlite3
import os
def create_db():
print 'Creating DB'
db = sqlite3.connect('database.sqlite')
cursor = db.cursor()
cursor.execute('''drop table if exists hosts'''), cursor.execute('''drop table if exists vulns'''), cursor.execute('''drop table if exists cves''')
db.commit()
cursor.execute('''CREATE TABLE hosts(id INTEGER PRIMARY KEY, operating_system TEXT, host_ip TEXT, netbios_name TEXT)''')
cursor.execute('''CREATE TABLE vulns(pluginID INTEGER, pluginName TEXT, severity INTEGER, description TEXT, host_id INTEGER PRIMARY KEY, FOREIGN KEY(host_id) REFERENCES hosts(id))''')
cursor.execute('''CREATE TABLE cves(pluginID TEXT, cve TEXT, host_id INTEGER PRIMARY KEY, FOREIGN KEY(host_id) REFERENCES hosts(id))''')
db.commit()
db.close()
def delete_db():
answer = raw_input("Would you like to delete the database?")
if answer == "y":
os.remove('database.sqlite')
else:
pass
def get_details(nessus_file):
print "Getting Details"
db = sqlite3.connect('database.sqlite')
cursor = db.cursor()
try:
tree = ET.parse(nessus_file)
for reporthost in tree.findall('/Report/ReportHost'):
netbios_name = None
operating_system = None
for tag in reporthost.findall('.//HostProperties/tag'):
if tag.get('name') == 'netbios-name':
netbios_name = tag.text
elif tag.get('name') == 'operating-system':
operating_system = tag.text
elif tag.get('name') == 'host-ip':
host = tag.text
if netbios_name == None:
netbios_name = 'N/A'
if operating_system == None:
operating_system = 'N/A'
for item in reporthost.findall('ReportItem'):
sev = item.get('severity')
name = item.get('pluginName')
description = item.findtext('description')
pluginid = item.get('pluginID')
print netbios_name
print operating_system
print host
print name
print sev
print description
print pluginid
cursor.execute('INSERT INTO hosts(host_ip, netbios_name, operating_system) VALUES(?,?,?)', (host, netbios_name, operating_system,))
cursor.execute('INSERT INTO vulns(pluginName, severity, description, pluginID) VALUES(?,?,?,?)', (name, sev, description, pluginid,))
for cve in item.getiterator('cve'):
cursor.execute('INSERT INTO cves(cve, pluginID) VALUES(?,?)', (cve.text, pluginid,))
db.commit()
db.close()
except Exception as e:
print e
exit()
create_db()
get_details('file.nessus')
delete_db()
Aucun commentaire:
Enregistrer un commentaire