手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python:MySQL备份脚本及删除指定目录下过期文件

[日期:2014-03-20] 来源:Linux社区  作者:鸟哥のlinux [字体: ]

最近在学习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扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

linux
相关资讯       MySQL备份脚本 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款