Skip to content

Instantly share code, notes, and snippets.

@SalcidoJesus
Created August 4, 2023 18:09
Show Gist options
  • Save SalcidoJesus/e35a1f05409daf20f23982b3f0ace909 to your computer and use it in GitHub Desktop.
Save SalcidoJesus/e35a1f05409daf20f23982b3f0ace909 to your computer and use it in GitHub Desktop.
Python script to backup mysql database and compress it on zip
import os
import time
import datetime
import zipfile
import subprocess
HOST = 'localhost'
PORT = '3306'
DB_USER = 'root'
DB_PASS = ''
# if you want to backup only one database
# databases = ('db1',)
databases = ('db1', 'db2', 'db3')
def get_dump(database, folder_name):
filestamp = time.strftime('%Y-%m-%d_%I-%p')
cmd = f"/usr/bin/mariadb-dump -h {HOST} -P {PORT} -u {DB_USER} -p{DB_PASS} {database} > {folder_name}/{database}_{filestamp}.sql"
subprocess.run(cmd, shell=True)
print("\n|| Database dumped to " + folder_name + "/" + database + "_" + filestamp + ".sql || ")
def create_zip_folder(folder_name):
with zipfile.ZipFile(folder_name + '.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
for folder_name, _, files in os.walk(folder_name):
for file in files:
zipf.write(os.path.join(folder_name, file))
async def main():
# filename
fecha_hoy = datetime.datetime.now().strftime('%Y-%m-%d')
if not os.path.exists(fecha_hoy):
os.makedirs(fecha_hoy)
for database in databases:
get_dump(database, fecha_hoy)
print('--- Backup completed ---')
await asyncio.sleep(5)
create_zip_folder(fecha_hoy)
print('\n---The zip file has been created---')
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment