Sunday, January 25, 2015

python mysql backup script 1

root@vm1:~/pyscript# cat back.py
#!/usr/bin/python
#Python 2.7.6
db_name_file = '/root/pyscript/dbname.txt'
backup_dest = '/root/pyscript/sqlbackup/'
import os
import time
import datetime
dbhost = 'localhost'
dbuser = 'root'
dbpass = 'redhat'
datetime = time.strftime("%Y-%m-%d_%H-%M-%S")
backuppathwithDT = backup_dest + datetime
#create directory if it does not exist
if not os.path.exists(backuppathwithDT):
    os.makedirs(backuppathwithDT)
print "Checking for db names in file"
if os.path.exists(db_name_file):
    file1 = open(db_name_file)
    multi = 1
    print "Database names found"
    print "starting backup of databases.. "
else:
    print "Database file not found in file"
    multi = 0

#Starting backup
if multi:
    in_file = open(db_name_file,"r")
    flength = len(in_file.readlines())  ##in_file.readlines() returns a list
    in_file.close()
    p = 1
    dbfile = open(db_name_file,"r")
   
    while p <= flength:
        db = dbfile.readline()
        db = db[:-1]  #deletes extra line
        dumpcmd = "mysqldump -u " + dbuser + " -p" + dbpass + " " + db + " > " + backuppathwithDT + "/" + db + ".sql"
        os.system(dumpcmd)
        p = p + 1
    dbfile.close()
else:
    print "no database to dump"
print "Exiting..."

No comments:

Post a Comment