Python:MySQL备份脚本及删除指定目录下过期文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:MySQL备份脚本及删除指定目录下过期文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2418字,纯文字阅读大概需要4分钟。
内容图文
![Python:MySQL备份脚本及删除指定目录下过期文件](/upload/InfoBanner/zyjiaocheng/546/90fdf955d1434cc09bdda77595241dc5.jpg)
最近在学习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系统信息
内容总结
以上是互联网集市为您收集整理的Python:MySQL备份脚本及删除指定目录下过期文件全部内容,希望文章能够帮你解决Python:MySQL备份脚本及删除指定目录下过期文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。