一、备份脚本

#!/usr/bin/python

import os
import time
import datetime

# MySQL database details to which backup to be done. Make sure below user having enough privileges to take databases backup. 
# To take multiple databases backup, create any file like /backup/dbnames.txt and put databses names one on each line and assignd to DB_NAME variable.

DB_HOST = 'localhost'
DB_USER = 'USER_NAME'
DB_USER_PASSWORD = 'USER_PASSWORD'
BACKUP_PATH = 'FILE_PATH'

# Getting current datetime to create seprate backup folder like "12012013-071334".
DATETIME = time.strftime('%m%d%Y-%H%M%S')

TODAYBACKUPPATH = BACKUP_PATH + DATETIME

# Checking if backup folder already exists or not. If not exists will create it.
print "creating backup folder" 
if not os.path.exists(TODAYBACKUPPATH):
    os.makedirs(TODAYBACKUPPATH)

# Show the databases table:
database_list_command = "mysql -u %s -p%s -h %s --silent -N -e 'show databases'" % (DB_USER, DB_USER_PASSWORD, DB_HOST)

# Starting actual database backup process.
if database_list_command:
    for database in os.popen(database_list_command).readlines():
        database = database.strip()
        if database == 'information_schema': #ignore the database
            continue
        if database == 'performance_schema': #ignore the database
            continue
        if database == 'test': #ignore the test database
            continue
        if database == 'keystone': #backup keystone database and token table structure
            tokendumpcmd = "mysqldump -d keystone token -u " + DB_USER + " -p" + DB_USER_PASSWORD +  " > " + TODAYBACKUPPATH + "/" +  "keystone_token.sql" 
            keystone_dumpcmd = "mysqldump --ignore-table=keystone.token keystone -u " + DB_USER + " -p" + DB_USER_PASSWORD +  " > " + TODAYBACKUPPATH + "/" +  "keystone.sql" 
            os.system(tokendumpcmd)
            os.system(keystone_dumpcmd)
            continue
        dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + database + " > " + TODAYBACKUPPATH + "/" + database + ".sql" 
        os.system(dumpcmd)
else:
    print "Backup FAILED" 

# Bacup completed
print "Backup script completed" 
print "Your backups has been created in '" + TODAYBACKUPPATH + "' directory" 
二、加入crontab计划表
1 0 * * * /usr/bin/python backup.py >> /dev/null 2>&1


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐