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系统信息

logo.gif

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值