Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2577
  • 博文数量: 3
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2016-09-18 11:29
文章分类
文章存档

2016年(3)

我的朋友
最近访客

分类: Python/Ruby

2016-09-18 11:40:35

最近在学习Python,之前用shell实现的备份脚本,在python下要如何写呢? 这也是一个学习的好方法吧,于是结合生产环境需要,编写了Python数据库备份脚本。
可指定数据库备份,如有要备份所有的数据库,可使用 –all-database 这个参数。并且删除了备份文件的过期时间,如果想把备份日志记录下来,那么可以参考open相关资料。
贴上脚本:MysqlBackup.py


  1. #!/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,对python还不够熟习,总觉得这个脚本用shell写应该更简单也更容易些。

就功能上来说,该脚本已经实现了我想要的效果,不过该脚本还不够通用性,还有更多可以完善的地方。目前该脚本在python2.4下运行良好。同时,蚊子在脚本中加入了对python版本的判断,理论上2.7下也应该可以正常使用。有环境的朋友可以帮忙测试一下。

该脚本不完善的地方在于,只能支持一级目录下的文件删除,还不支持目录递归。同时过期文件的定义只能按week来做。

脚本如下:


  1. #! /usr/bin/env python
    # -*- coding=utf-8 -*-
    import sys
    import os
    import time,datetime
     
    # 定义需要删除文件的目录
    dir = '/data/webbak/'
    # 被删除文件写入日志文件
    logdir = '/var/log'
    logfile = os.path.join(logdir, 'delete.log')
     
    # 获取当前系统python版本
    ver = sys.version
    ver = ver.split(' ')
    ver = ver[0]
     
    # 将"Wed Jul  4 13:25:59 2012"格式的时间转成“2012-07-02 14:50:15”格式的时间
    # version是当前系统python版本号
    # time是"Wed Jul  4 13:25:59 2012"格式的时间
    # 函数返回"2012-07-02 14:50:15"格式的时间
    def string2time(str_time, version = ver):
    version_l = version.split('.')[0:2]
    ver = version_l[0] + '.' + version_l[1]
    if (ver == '2.7'):
    f_time = datetime.datetime.strptime(str_time, time_format)
    f_time = f_time.strftime('%Y-%m-%d %H:%M:%S')
    return f_time
    elif(ver == '2.4'):
    f_time = time.strptime(str_time, time_format)
    f_time = datetime.datetime(*f_time[0:6])
    return f_time
     
    # 时间格式
    time_format = "%a %b %d %H:%M:%S %Y"
    # 取得当前时间
    today = datetime.datetime.now()
    # 定义4个星期
    four_weeks = datetime.timedelta(weeks=6)
    # 4星期前的日期
    four_weeks_ago = today - four_weeks
    # 将时间转成timestamps
    four_weeks_ago_timestamps = time.mktime(four_weeks_ago.timetuple())
    # 列出目录中的所有文件
    files = os.listdir(dir)
    # 打开要删除的文件日志
    fh = open(logfile, "w+")
    # 遍历文件,打印出文件的创建时间
    for f in files:
    # 忽略掉.开头的文件
    if f.startswith('.'):
    continue
    # 忽略掉当前目录下的目录
    if os.path.isdir(os.path.join(dir,f)):
    continue
    # 获得文件的modify时间,并转换成timestamp格式
    file_timestamp = os.path.getmtime(os.path.join(dir, f))
    file_time_f = string2time(time.ctime(file_timestamp))
    if float(file_timestamp) <= float(four_weeks_ago_timestamps):
    fh.write(str(today) + "\t" + str(file_time_f) + "\t" + os.path.join(dir,f) + "\n")
    os.remove(os.path.join(dir,f))
    # 关闭文件
    fh.close()


阅读(207) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:nginx负载均衡实例

给主人留下些什么吧!~~