MySQL : Dump de todas databases com Python

Neste post será abordado como escrever um simples script para realizar dump de todas databases.

#!/bin/python

import os
import time
import datetime
import  shutil

PATH = '/app/mysql/'  #Ponto de montagem do Storage
DB_HOST="host"
DB_USER="root"
DB_PASSWD="passwd"
DATETIME = time.strftime('%A-%d.%m.%Y')

#Check Dir
if os.path.exists(PATH) :
        log = 'Dir exists'
else :
        os.mkdir(PATH)
        print 'Dir has been created'

#Go to directory
os.chdir("/app/mysql")


#List all databases
GET_DB_LIST = "mysql -u %s -p%s -h % --silent -N -e 'show databases'" % (DB_USER, DB_PASSWD, DB_HOST)

#Execute mysqldump in the list
for DB_NAME in os.popen(GET_DB_LIST).readlines():
        DB_NAME = DB_NAME.strip()
        if DB_NAME == 'information_schema':
                continue
        if DB_NAME == 'performance_schema':
                continue
        if DB_NAME == 'mysql':
                os.popen("mysqldump -u %s  --events --ignore-table=mysql.event -p%s -h %s -e --opt -c %s | gzip -c > %s.gz" % (DB_USER,DB_USER_PASSWD,DB_HOST,DB_NAME,DB_NAME+"_"+DATETIME))
        else:
                os.popen("mysqldump -u %s -p%s -h %-e --opt -c %s | gzip -c > %s.gz" % (DB_USER,DB_USER_PASSWD,DB_HOST,DB_NAME,DB_NAME+"_"+DATETIME))