Python Script: Take backup of mysql database

This scripts assumes you want to take backup on the same server.

If you want the backup on a different sever, see below:


import os
import time
import datetime

date1 = time.strftime('%Y%m%d%H%M%S')
f = open('/root/mypython/dblist.txt')  # this files contains the name of databases
line = f.readline()
words = line.split()
for word in words:
    cmd = "mysqldump -u root -pabhishek {0} > {0}_{1}.sql".format(word, date1) 
# takes backup in the same location as script

    cmd2 = "zip {0}_{1}.zip {0}_{1}.sql".format(word, date1)  
 # zips the backup just taken

    cmd3 = "rm -f {0}_{1}.sql".format(word, date1) 
# deletes the .sql backup just taken. after this step only .zip backup remains. remove this line if u need both .sql and .zip

    cmd4 = " mv {0}_{1}.zip /backupdb ".format(word, date1) 

# move the zip files to specified location on the same server, use scp if you need to take backup on another server.

    if os.system(cmd4)== 0:
       result = "Backup Successful"  

# if all process succeed, prints at terminal.