Created
February 18, 2019 22:19
-
-
Save edermi/3382b95f17a5e38b2148c45cbe0ed620 to your computer and use it in GitHub Desktop.
Quick and dirty python3 nmap/masscan xml to sqlite3 converter. Only converts address, port and if state is 'open' or not
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# For untrusted XML input, use a hardened parser, see https://docs.python.org/3/library/xml.html | |
import xml.etree.ElementTree as ET | |
import sqlite3 | |
import argparse | |
import sys | |
def parseArgs(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("scanfile") | |
parser.add_argument("databasefile") | |
parser.add_argument("tablename") | |
args = parser.parse_args() | |
return args.scanfile, args.databasefile, args.tablename | |
def parse_xml(scanfile): | |
result = [] | |
tree = ET.parse(scanfile) | |
root = tree.getroot() | |
for host in root.findall("host"): | |
try: | |
addr = host.find("address").get("addr") | |
port = host.find("ports").find("port").get("portid") | |
state = host.find("ports").find("port").find("state").get("state") | |
result.append((addr, port, state=="open")) | |
print("{}:{} is {}".format(addr,port,state)) | |
except AttributeError: | |
continue | |
return result | |
def prepare_db(database, tablename, data): | |
if tablename not in ["nmap", "masscan"]: | |
print("Tablename must either be nmap or masscan") | |
sys.exit(1) | |
conn = sqlite3.connect(database) | |
c = conn.cursor() | |
if tablename == "nmap": | |
c.execute('''DROP TABLE IF EXISTS nmap''') | |
c.execute('''CREATE TABLE nmap (address text, port integer, open integer)''') | |
c.executemany('''INSERT INTO nmap VALUES (?,?,?)''', data) | |
elif tablename == "masscan": | |
c.execute('''DROP TABLE IF EXISTS masscan''') | |
c.execute('''CREATE TABLE IF NOT EXISTS masscan (address text, port integer, open integer)''') | |
c.executemany('''INSERT INTO masscan VALUES (?,?,?)''', data) | |
else: | |
sys.exit(1) | |
conn.commit() | |
conn.close() | |
# python3 xml2db.py scan.masscan.xml results.sqlite masscan | |
def main(): | |
scanfile, database, tablename = parseArgs() | |
parsed = parse_xml(scanfile) | |
prepare_db(database, tablename, parsed) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment