Python Script: Taking mysql backup and moving backup to a remote server

Hello Friends,

Below is the script to take mysql backup and moving it to a remote server.


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 = " scp {0}_{1}.zip root@ ".format(word, date1)
    if os.system(cmd4)== 0:
        result = "Backup Successful"


Things to be remember

1. The cmd4 command do a scp. You must have key based login enable from your server to remote server otherwise you will be asked password of remote server, which the script can't provide.

To enable key based login, see below:

2. The first line of the script makes it executable, so for scheduling backup, you just need to enter full path in crontab, e.g. if you want to run this script every ten minutes do following entry in crontab 
*/10 * * * * /home/

3. Make script executable by chmod 777 or whatever permission you want.