发布时间:2019-08-06 09:14:09编辑:auto阅读(1503)
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
上一篇: Python学习之MySQLdb模块
下一篇: python系统信息模块psutil
47494
45795
36793
34325
28968
25598
24443
19611
19111
17633
5466°
6048°
5570°
5638°
6573°
5376°
5378°
5885°
5855°
7171°