mysql database backu
Mysql database backup use python scripts
- #!/usr/bin/env Python
- #coding=utf8
- #author : itnihao
- #mail : itnihao@qq.com
- #source : Http://code.taobao.org/p/python2/src/trunk/
- #version:1.0
-
- '''
- 功能:mysql备份。用mysqldump对mysql中各库进行备份
- 1.user,pass,host,path,del参数为变量
- 2.默认备份删除周期为5天,备份以天为单位
- 3.默认备份路径为/mysql_backup,如果不存在会建立此目录
- 4.用法为加执行权限,定时任务运行
- '''
- import os,subprocess,datetime
-
- '''设置变量'''
- MYSQL_USER = 'root'
- MYSQL_PASS = 'pass'
- MYSQL_HOST = 'localhost'
- DEL_DAYS = 5
- BACK_PATH = '/mysql_backup'
-
- '''''时间设置'''
- CUR_TIME = datetime.date.today()
- AGo_TIME = datetime.timedelta(days=DEL_DAYS)
- DEL_TIME = CUR_TIME - AGO_TIME
- DATABASE = ''
-
-
- '''备份函数'''
- def mysqldump():
- if os.path.isdir(BACK_PATH):
- os.chdir(BACK_PATH)
- else:
- os.mkdir(BACK_PATH)
- os.chdir(BACK_PATH)
- database_cmd=subprocess.Popen("mysql -u%s -p%s -h%s -e 'show databases'|grep -v Database|grep -v infORMation" %(MYSQL_USER,MYSQL_PASS,MYSQL_HOST),stdout=subprocess.PIPE,shell=True)
- DATABASE_NAME=database_cmd.stdout.read().split()
- for DATABASE in DATABASE_NAME:
- MYSQLDUMP_FILENAME="/mysql_backup/%s%s.sql"%(CUR_TIME,DATABASE)
- subprocess.call("mysqldump -u%s -p%s -h%s %s>%s" %(MYSQL_USER,MYSQL_PASS,MYSQL_HOST,DATABASE,MYSQLDUMP_FILENAME),shell=True)
- if os.path.isfile('${DEL_TIME}${DATABASE}.sql'):
- subprocess.call("rm ${DEL_TIME}${DATABASE}.sql",shell=True)
-
- mysqldump()
脚本下载地址http://code.taobao.org/p/python2/src/trunk/mysql_backup.py
相关文章