Python 数据库备份脚本

本文介绍了一个使用Python编写的MySQL数据库备份脚本。该脚本能够实现自动化备份,并支持单个或多个数据库的备份操作。它通过读取数据库名称文件进行批量备份,备份文件将按日期保存在指定目录下。

#!/usr/bin/python
##########################################################
# Created date: 2017/12/7
# Last modified: 201712/7
# Tested with : Python 2.6.6
# Script Revision: Mysql_dump.py
##########################################################

import os
import time
import datetime

DB_HOST = '192.168.1.203'
DB_USER = 'root'
DB_USER_PASSWORD = '123456'
DB_NAME = '/data/DB_back/dbnames.txt'
#DB_NAME = 'Var'
Back_up_dir = '/data/DB_back/'
DATETIME = time.strftime('%Y%m%d')
Dir_backup = Back_up_dir + DATETIME


print "creating backup folder"
if not os.path.exists(Dir_backup):
os.makedirs(Dir_backup)
# 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 <= flength:
db = dbfile.readline() # reading database name from file
db = db[:-1] # deletes extra line
dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + Dir_backup + "/" + db + ".sql"
os.system(dumpcmd)
p = p + 1
dbfile.close()
else:
db = DB_NAME
dumpcmd = "mysqldump -u " + DB_USER + " -p" + DB_USER_PASSWORD + " " + db + " > " + Dir_backup + "/" + db + ".sql"
os.system(dumpcmd)
print "Backup script completed"
print "Your backups has been created in '" + Dir_backup + "' directory"

转载于:https://www.cnblogs.com/Van214/p/7999069.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值