How to use the apsw.Shell function in apsw

To help you get started, we’ve selected a few apsw examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / extractor.py View on Github external
def askfortimeline(case): #If the user opts into reports, ask if they want to make a timeline too
	print("Create a timeline of all supported events? (Takes significantly longer)")
	answer = input('[Y/N]')
	answer = answer.upper()
	if answer == 'Y':
		if not os.path.exists(os.path.join(case, "reports")):
			os.makedirs(os.path.join(case, "reports"))
		if not os.path.exists(os.path.join(case, "reports", "timeline")):
			os.makedirs(os.path.join(case, "reports", "timeline"))
		tldb = os.path.join(case, "reports", "timeline.db")
		if os.path.isfile(tldb):
			os.remove(tldb)
		tloutopen = io.StringIO()
		tlconnection = apsw.Connection(tldb)
		dbshell = apsw.Shell(stdout=tloutopen, db=tlconnection)
		dbshell.process_sql("CREATE TABLE timeline(_id INTEGER PRIMARY KEY NOT NULL, service, message, timestamp)")
		return(True)
	elif answer == 'N':
		return(False)
	else:
		print("Unrecognised answer. Defaulting to 'N'")
		return(False)
github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / google_calendar / extract.py View on Github external
for row in dbcursor1.execute("select distinct account_name from calendars"):
		for entry1 in row:
			accountdir = os.path.join(extractdir, str(entry1))		
			if not os.path.exists(accountdir):
				os.makedirs(accountdir)	

			for row2 in dbcursor2.execute("select name from calendars where account_name = '" + str(entry1) + "'"):
				for entry2 in row2:	
					caldir = os.path.join(accountdir, str(entry2))		
					if not os.path.exists(caldir):
						os.makedirs(caldir)	
					for row3 in dbcursor3.execute("select _id from calendars where name = '" + str(entry1) + "' AND account_name = '" + str(entry2) + "'"):
						for entry3 in row3:
							filepath = os.path.join(caldir, "Events.txt")
							eventfile = open(filepath, "w", encoding='utf8')
							SQLShell = apsw.Shell(stdout=eventfile, db=dbconnection)
							try:
								SQLShell.process_command(".header on")
								SQLShell.process_sql("select * from events where calendar_id = " + str(entry3))
							except Exception:
								print("Error: Could not process " + str(entry1) + " in " + str(entry2) + ".")
								errors = errors + 1
							eventfile.close()
	if not errors == 0:
		print(errors +" error(s) occured in the extraction process!")
github inportb / playground / Pinako / webquery / webquery.py View on Github external
def Rowid(self):
		return self.rowid
	def Next(self):
		try:
			self.row = self.iter.next()
			self.rowid += 1
		except StopIteration:
			pass
	def Eof(self):
		return self.iter is None
	def Close(self):
		pass

if __name__ == '__main__':
	import sys, re
	shell = apsw.Shell()
	mod = WebQueryModule()
	shell.db.createmodule('webquery',mod)
	loaded = []
	for fn in sys.argv[1:]:
		tbl = re.sub(r'\W','_',fn)
		if tbl.endswith('_yml'):
			tbl = tbl[:-4]
		sql = 'CREATE VIRTUAL TABLE %s USING webquery(%s);'%(tbl,fn)
		try:
			shell.process_sql(sql)
			loaded.append('> '+sql+'\r\n')
		except KeyboardInterrupt:
			raise
		except:
			pass
	shell.cmdloop(intro=('SQLite version %s (APSW %s)\r\nEnter ".help" for instructions\r\nEnter SQL statements terminated with a ";"\r\n'%(apsw.sqlitelibversion(),apsw.apswversion()))+''.join(loaded))
github plasticityai / magnitude / pymagnitude / third_party / _apsw / tools / docupdate.py View on Github external
op.append("")
        continue
    if line==".. speedtest-end":
        incomment=False
    if incomment:
        continue
    op.append(line)

op="\n".join(op)
if op!=benchmark:
    open("doc/benchmarking.rst", "wt").write(op)

# shell stuff

import apsw, StringIO
shell=apsw.Shell()
incomment=False
op=[]
for line in open("doc/shell.rst", "rtU"):
    line=line.rstrip()
    if line==".. help-begin:":
        op.append(line)
        incomment=True
        op.append("")
        op.append(".. code-block:: text")
        op.append("")
        s=StringIO.StringIO()
        def tw(*args):
            return 80
        shell.stderr=s
        shell._terminal_width=tw
        shell.command_help([])
github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / whatsapp / extract-whatsapp.py View on Github external
tmpfile = open(dbtmp, "rb")
		tmptogzip = tmpfile.read()
		finaldb = open(dbdecrypt, "wb")
		d = zlib.decompressobj(16+zlib.MAX_WBITS)
		decompressdata=d.decompress(tmptogzip)
		finaldb.write(decompressdata)
		tmpfile.close()
		finaldb.close()
		
		#os.system('bin\\gzip.exe -d < "' + dbtmp + '" > "' + dbdecrypt + '"' if os.name == 'nt' else 'gzip -d < "' + dbtmp + '" > "' + dbdecrypt + '" 2>&1' )
		print("--> Extracting WhatsApp data\n\n")
		txtoutput = os.path.join(case, "extracted data", "whatsapp", "messages.txt")
		txtoutfile = open(txtoutput, 'w', encoding='utf8')
		sqlconnection = apsw.Connection(dbdecrypt)
		sqlshell = apsw.Shell(stdout=txtoutfile, db=sqlconnection)
		sqlshell.process_command('.header on')
		sqlshell.process_sql('select * from messages')
		txtoutfile.close()
		
		os.remove(dbtmp)
		os.remove(dbnohead)

	else:
		print("--> Not extracting WhatsApp data. Reason: Not found\n\n")
github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / tinder / extract.py View on Github external
def sql(case, dbpath):
	print("--> Extracting Tinder information")
	db = os.path.join (dbpath, "tinder.db" )
	output = os.path.join(dbpath, '..', 'output.txt')
	openoutput = open(output, 'w')
	dbconn = apsw.Connection(db)
	dbshell = apsw.Shell(stdout=openoutput, db=dbconn)
	try:
		dbshell.process_command(".header on")
		dbshell.process_sql("select * from messages")
		openoutput.close()
	except Exception:
		print("Extract Failed")
github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / facebook / extract.py View on Github external
def sql(case, dbdir):

	user = dbdir
	print( "--> Extracting results from Facebook databases\n\n")
	database = os.path.join(user, "threads_db2")
	outputfile = os.path.join(user, "..", "threads_db2.txt")
	output = open(outputfile, 'w', encoding='utf8')
	extractSQLconnect = apsw.Connection(database)
	SQLShell = apsw.Shell(stdout=output, db=extractSQLconnect)
	try:
		SQLShell.process_command(".header on")
		SQLShell.process_sql("select * from messages")
	except:
		print("Could not extract messages")
	output.close()

	database = os.path.join(user, "contacts_db2")
	outputfile = os.path.join(user, "..", "contacts_db2.txt")
	output = open(outputfile, 'w', encoding='utf8')
	extractSQLconnect = apsw.Connection(database)
	SQLShell = apsw.Shell(stdout=output, db=extractSQLconnect)
	try:
		SQLShell.process_command(".header on")
		SQLShell.process_sql("select * from contacts")
	except Exception:
github norbusan / calibre-debian / src / calibre / db / backend.py View on Github external
uv = int(self.user_version)

        with TemporaryFile(suffix='.sql') as fname:
            if sql is None:
                callback(_('Dumping database to SQL') + '...')
                with codecs.open(fname, 'wb', encoding='utf-8') as buf:
                    shell = Shell(db=self.conn, stdout=buf)
                    shell.process_command('.dump')
            else:
                with lopen(fname, 'wb') as buf:
                    buf.write(sql if isinstance(sql, bytes) else sql.encode('utf-8'))

            with TemporaryFile(suffix='_tmpdb.db', dir=os.path.dirname(self.dbpath)) as tmpdb:
                callback(_('Restoring database from SQL') + '...')
                with closing(Connection(tmpdb)) as conn:
                    shell = Shell(db=conn, encoding='utf-8')
                    shell.process_command('.read ' + fname.replace(os.sep, '/'))
                    conn.execute('PRAGMA user_version=%d;'%uv)

                self.close(unload_formatter_functions=False)
                try:
                    atomic_rename(tmpdb, self.dbpath)
                finally:
                    self.reopen()
github AFFT-520 / Android-Free-Forensic-Toolkit / pkg / win32 / build / src / extractor / accounts / extract.py View on Github external
extractdir = os.path.join(case, "extracted data")
	if not os.path.exists(extractdir):
		os.makedirs(extractdir)
	extractdir = os.path.join(extractdir, "accounts")
	
	
	shutil.copytree(os.path.join(userdata, "system", "users"), os.path.join (case, "extracted data", "accounts"))
	for dirname, dirnames, filenames in os.walk(extractdir):
		for subdirname in dirnames:		
			user = os.path.join(extractdir, subdirname)	
			database = os.path.join(user, "accounts.db")
			outputfile = os.path.join(user, "accounts.txt")
			output = open(outputfile, 'w', encoding='utf8')
			extractSQLconnect = apsw.Connection(database)
			SQLShell = apsw.Shell(stdout=output, db=extractSQLconnect)
			SQLShell.process_command(".header on")
			SQLShell.process_sql("select * from accounts")
			output.close()