Skip to content

Instantly share code, notes, and snippets.

@Kungergely
Last active January 10, 2022 11:36
Show Gist options
  • Save Kungergely/b18780e7b77b362d95187f2ab489f5c3 to your computer and use it in GitHub Desktop.
Save Kungergely/b18780e7b77b362d95187f2ab489f5c3 to your computer and use it in GitHub Desktop.
A Py3 script for backing up the places.sqlite file (Firefox history) which's known to become corrupt and lose contents during crashes. It should work on both Windows and Linux with backing up the file from the first FF profile folder found. It requires a working Py3 installation and on Windows it should be scheduled using pythonw.exe to avoid CL…
import gzip, os, platform, shutil, sqlite3
from datetime import datetime
# The paths are somewhat different on Linux and Windows
if platform.system()=="Windows":
destdir="D:\\FF backups"
srcdir=os.environ["APPDATA"]+"\\Mozilla\\Firefox\\Profiles"
elif platform.system()=="Linux":
destdir="/media/backup"
srcdir=os.environ["HOME"]+"/.mozilla/firefox"
else:
print("Sorry, only Windows and Linux is supported at the moment")
exit()
if not os.path.exists(destdir): os.makedirs(destdir)
profiledir=next(os.walk(srcdir))[1][0]
curtime=datetime.now().strftime("-%Y-%m-%d_%H-%M")
dstFile=destdir+"/places"+curtime+".sqlite"
try:
srcConn = sqlite3.connect(srcdir+"/"+profiledir+"/places.sqlite")
dstConn = sqlite3.connect(dstFile)
with dstConn:
srcConn.backup(dstConn, pages=5)
except sqlite3.Error as error:
print("SQLite database connection error: ",error)
finally:
if dstConn:
dstConn.close()
srcConn.close()
# gzipping the result
gz_in = open(dstFile, "rb")
#print(dstFile)
gz_out = gzip.open(dstFile+'.gz', 'wb')
shutil.copyfileobj(gz_in, gz_out)
gz_out.close()
gz_in.close()
# Removing the destination file only after all the close operations
# have successfully completed to make sure that there's a working copy
os.remove(dstFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment