Rumah >pangkalan data >tutorial mysql >Python:MySQL备份脚本及删除指定目录下过期文件
最近在学习Python,之前用shell实现的备份脚本,在python下要如何写呢? 这也是一个学习的好方法吧,于是结合生产环境需要,编写
最近在学习Python,之前用shell实现的备份脚本,,在python下要如何写呢? 这也是一个学习的好方法吧,于是结合生产环境需要,编写了Python数据库备份脚本。
可指定数据库备份,如有要备份所有的数据库,可使用 –all-database 这个参数。并且删除了备份文件的过期时间,如果想把备份日志记录下来,那么可以参考open相关资料。
贴上脚本:MysqlBackup.py
#!/usr/bin/env python
# Filename: mysqlbackup.py
# version 0.01
# author:Robert Lin
# email:linlianpengit@sina.com
# date:2013-08-09
import os
import time
import sys
import datetime
from stat import *
# mysql user
User = 'root'
# mysql password
Passwd = '123456'
# mysqldump command
Mysqlcommand = '/usr/bin/mysqldump'
# gzip command
Gzipcommand = '/bin/gzip'
# you want backup mysql database
Mysqldata = ['HQ', 'forum_us']
# you want backup to dir
Tobackup = '/dbbak/'
for DB in Mysqldata:
# backup file name
Backfile = Tobackup + DB + '-' + time.strftime('%Y-%m-%d') + '.sql'
# gzip file name
Gzfile = Backfile +'.gz'
if os.path.isfile(Gzfile):
print Gzfile + " is already backup"
else:
# backup command
Back_command = Mysqlcommand + ' -u' + User + ' -p' + Passwd + ' -P3306 ' + DB + ' > ' + Backfile
if os.system(Back_command)==0:
print 'Successful backup to', DB + ' to ' + Backfile
else:
print 'Backup FAILED'
# gzip command
Gzip_command = Gzipcommand + ' ' + Backfile
if os.system(Gzip_command)==0:
print 'Successful Gzip to',Gzfile
else:
print 'Gzip FAILED'
# Delete back file
# show file list
filelist=[]
filelist=os.listdir(Tobackup)
# delete Gzfile 5 days ago
for i in range(len(filelist)):
ft=time.gmtime(os.stat(Tobackup+filelist[i])[ST_MTIME])
ftl=time.strftime('%Y-%m-%d',ft)
year,month,day=ftl.split('-')
ftll=datetime.datetime(int(year),int(month),int(day))
localt=time.gmtime()
localtl=time.strftime('%Y-%m-%d',localt)
year,month,day=localtl.split('-')
localtll=datetime.datetime(int(year),int(month),int(day))
days=(localtll-ftll).days
if days >5:
try:
os.remove(Tobackup+filelist[i])
print 'delete is ok'
except:
log=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+" remove "+Tobackup+filelist[i]+" fail \n"
print log
Python 的详细介绍:请点这里
Python 的下载地址:请点这里
推荐阅读:
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]
Python脚本获取Linux系统信息