这是一个简单的python脚本使用python脚本备份mysql数据库。这个脚本是使用Python2.6.6编写,我建议安装Python 2.6.6或更高版本后才能使用。
如何使用脚本:
这个脚本是非常容易使用,下载或在本地系统上复制此脚本并用Python执行它。这个脚本能够对多个数据库备份
单个数据库备份:如果你想使用这个脚本对单一的数据库备份,编辑下面的脚本。例如数据库名称为MYDB。
DB_NAME = 'mydb'
多个数据库备份:要对多个数据库备份,创建这样一个/backup/dbnames.txt文本文件,并添加数据库名,每行一个如下图所示
# cat /backup/dbnames.txt
database1
mydb
而这个文件添加到脚本如下图所示。
DB_NAME = '/backup/dbnames.txt'
更改备份位置:您可以更改以下变量来更改备份路径的位置。
BACKUP_PATH = '/backup/dbbackup/'
下载脚本:
点击此处或使用以下命令从sourceforge.net下载脚本。
# wget http://sourceforge.net/projects/mysqldumppython/files/dbbackup.py
或者你可以简单地复制下面的脚本。
#!/usr/bin/python
###########################################################
#
# This python script is used for mysql database backup
# using mysqldump utility.
#
# Written by : Rahul Kumar
# Website: https://www.youcl.com
# Created date: Dec 03, 2013
# Last modified: Dec 03, 2013
# Tested with : Python 2.6.6
# Script Revision: 1.1
#
##########################################################
# Import required python libraries
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 = 'root'
DB_USER_PASSWORD = '_root_user_password_'
#DB_NAME = '/backup/dbnames.txt'
DB_NAME = 'db_name'
BACKUP_PATH = '/backup/dbbackup/'
# 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)
# Code for checking if you want to take single database backup or assinged multiple backups in DB_NAME.
print "checking for databases names file."
if os.path.exists(DB_NAME):
file1 = open(DB_NAME)
multi = 1
print "Databases file found..."
print "Starting backup of all dbs listed in file " + DB_NAME
else:
print "Databases file not found..."
print "Starting backup of database " + DB_NAME
multi = 0
# Starting actual database backup process.
if multi:
in_file = open(DB_NAME,"r")
flength = len(in_file.readlines())
in_file.close()
p = 1
dbfile = open(DB_NAME,"r")
while p " + TODAYBACKUPPATH + "/" + db + ".sql"
os.system(dumpcmd)
p = p + 1
dbfile.close()
else:
db = DB_NAME
dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + TODAYBACKUPPATH + "/" + db + ".sql"
os.system(dumpcmd)
print "Backup script completed"
print "Your backups has been created in '" + TODAYBACKUPPATH + "' directory"
如何执行脚本:
下载脚本之后使用下面的命令使脚本有可执行权限
# chmod +x dbbackup.py
然后执行这个脚本如下图所示
# python dbbackup.py
您还可以安排此脚本使用crontab的已固定时间间隔每天运行。在crontab命令中添加下面内容。
0 2 * * * /usr/bin/python dbbackup.py
了解更多的关于crontab在
20实用的调度作业例子 。 谢谢!使用这个脚本。