Refactored the writeFingerprint function. Added better exception handling for file writing.

This commit is contained in:
JohnE 2015-11-03 18:01:08 -08:00
parent c14f2d4177
commit f2606b31e5
4 changed files with 73 additions and 40 deletions

18
dbfp.py
View File

@ -3,10 +3,8 @@
# #
import os import os
import argparse import argparse
import time
import logging import logging
from libs import fingerprint from libs import fingerprint
from libs import toolbox
from libs import android from libs import android
from subprocess import Popen, PIPE, check_call from subprocess import Popen, PIPE, check_call
@ -30,11 +28,10 @@ def compareFingerprint(filein, filejson):
db.compareDB(filejson) db.compareDB(filejson)
# #
def createFingerprint(filein, fileout, verbose, app_name, app_ver, notes): def createFingerprint(filein, verbose, app_name, app_ver, notes):
db = fingerprint.DBSchema() db = fingerprint.DBSchema()
retVal = db.scanDBFile(filein) retVal = db.scanDBFile(filein)
if (retVal > 0): if (retVal > 0):
fh = open(fileout, "w")
if verbose: if verbose:
db.debugFingerprint() db.debugFingerprint()
if app_name: if app_name:
@ -43,8 +40,7 @@ def createFingerprint(filein, fileout, verbose, app_name, app_ver, notes):
db.setAppVer(app_ver) db.setAppVer(app_ver)
if notes: if notes:
db.setNotes(notes) db.setNotes(notes)
db.writeFingerprint(fh) db.writeFingerprint()
fh.close()
else: else:
print db.getErrorString(retVal) print db.getErrorString(retVal)
@ -107,8 +103,6 @@ def parseArgs():
print '***** ***** ***** *****' print '***** ***** ***** *****'
print ' DB Fingerprint' print ' DB Fingerprint'
print '***** ***** ***** *****\n' print '***** ***** ***** *****\n'
fileout = ''
timestr = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time()))
parser = argparse.ArgumentParser(description='Fingerprint a sqlite database based on its schema') parser = argparse.ArgumentParser(description='Fingerprint a sqlite database based on its schema')
parser.add_argument('-f', '--file', required=False) parser.add_argument('-f', '--file', required=False)
parser.add_argument('-fd', '--fpdir', required=False, help="path to dirctory of fingerprint files") parser.add_argument('-fd', '--fpdir', required=False, help="path to dirctory of fingerprint files")
@ -122,13 +116,11 @@ def parseArgs():
args = parser.parse_args() args = parser.parse_args()
if (args.file): if (args.file):
filename = toolbox.ToolBox.parseFilename(args.file) createFingerprint(args.file, args.verbose, args.app_name, args.app_version, args.notes)
fileout = filename + "_" + timestr + '.json'
createFingerprint(args.file, fileout, args.verbose, args.app_name, args.app_version, args.notes)
elif (args.file and args.fpdir): elif (args.file and args.fpdir):
compareFingerprintDir(args.file, args.fpdir) compareFingerprintDir(args.file, args.fpdir)
elif (args.fp): elif (args.file and args.fingerprint):
compareFingerprint(args.file, args.fp) compareFingerprint(args.file, args.fingerprint)
elif (args.pull): elif (args.pull):
fingerprintDir() fingerprintDir()
else: else:

8
libs/exceptions.py Normal file
View File

@ -0,0 +1,8 @@
#
#
#
class FingerprintWrite(Exception):
"""Problem writing the fingerprint to a file"""
pass

View File

@ -7,6 +7,7 @@ import sqlite3
import hashlib import hashlib
import time import time
from libs import toolbox from libs import toolbox
from libs.exceptions import FingerprintWrite
delimeter = "|" delimeter = "|"
@ -39,62 +40,94 @@ class DBSchema:
def __init__(self): def __init__(self):
self.conn = None self.conn = None
self.cur = None self.cur = None
self.dbName = ''
self.tableNames = [] self.tableNames = []
self.tables = {} self.tables = {}
self.tablesJson = {} self.tablesJson = {}
self.dbName = ""
self.app_name = "" self.app_name = ""
self.app_ver = "" self.app_ver = ""
self.notes = "" self.notes = ""
self.filein = ""
self.scanned = False
# self.jsonData = None # self.jsonData = None
return return
# #
def scanDBFile(self, filein): def scanDBFile(self, filein):
# try to open sqlite file """ read the database, populate the data into the class """
try: try:
(self.conn, self.cur) = self.__openDB(filein) (self.conn, self.cur) = self.__openDB(filein)
except Exception, e: except Exception, ex:
print e print ex
return -2 return -2
# extract file name from path+filename
try: try:
# extract file name from path+filename
self.dbName = toolbox.ToolBox.parseFilenameIncExt(filein) self.dbName = toolbox.ToolBox.parseFilenameIncExt(filein)
except: except:
self.dbName = filein self.dbName = filein
# read database schema
try: try:
# read database schema, parse the schema
self.__readDatabase() self.__readDatabase()
except Exception, e: except Exception, ex:
print e print ex
return -3 return -3
# flag is used to determine if the class has data
self.scanned = True
self.filein = filein
return 1 return 1
# #
def writeFingerprint(self, filein): def writeFingerprint(self):
self.DBSchema() if (not self.scanned):
retVal = self.scanDBFile(filein) return
if (retVal > 0):
try:
fileout = toolbox.ToolBox.getTimestampFilename(self.filein)
fh = open(fileout, "w") fh = open(fileout, "w")
self.__writeFingerprint(fh) try:
fh.close() self.__writeFingerprint(fh)
else: finally:
print self.getErrorString(retVal) fh.close()
except Exception, ex:
print ex
raise FingerprintWrite("Problem writing the fingerprint to a file")
#
def writeFingerprintFile(self, fileout):
if (not self.scanned):
return
try:
fh = open(fileout, "w")
try:
self.__writeFingerprint(fh)
finally:
fh.close()
except Exception, ex:
print ex
raise FingerprintWrite("Problem writing the fingerprint to a file")
# import fingerprint from a json file # import fingerprint from a json file
def importJson(self, filejson): def importJson(self, filejson):
""" import fingerprint from a json file """
self.tablesJson = self.__importJsonDBSchema(filejson) self.tablesJson = self.__importJsonDBSchema(filejson)
# #
def compareDB(self, filejson): def compareDB(self, filejson):
if (not self.scanned):
return
""" return the percentage of the match between two fingerprints """
self.tablesJson = self.__importJsonDBSchema(filejson) self.tablesJson = self.__importJsonDBSchema(filejson)
result = self.__DBSchemaCompare() result = self.__DBSchemaCompare()
print "[ Percetage == {}]".format(result) print "[ Percetage == {}]".format(result)
return result return result
# import fingerprint from a json file #
def __importJsonDBSchema(self, file_json): def __importJsonDBSchema(self, file_json):
""" import fingerprint from a json file """
tables = {} tables = {}
try: try:
fh = open(file_json, "r") fh = open(file_json, "r")

View File

@ -5,19 +5,19 @@ from libs import fingerprint
class FingerprintRunner: class FingerprintRunner:
""" """
Compare Finger Prints from a directory Compare Finger Prints from a directory
""" """
# #
def __init__(self): def __init__(self):
return return
# #
def dirCompare(self, folder): def dirCompare(self, folder):
return return
def compareFingerprint(self, fp1, fp2): def compareFingerprint(self, fp1, fp2):
pass pass