首页 > 编程语言 > 详细

python常用的备份脚本

时间:2016-03-11 19:08:49      阅读:235      评论:0      收藏:0      [点我收藏+]

脚本介绍:

1)备份源目录的文件

2)目标文件以tar 和bzip2的方式压缩之后放在当前日期文件夹下

4)备份文件以时间注释和执行脚本的用户命名

3)主要用到了时间模块,系统模块,和getpass模块

4)source 可以修改为想备份的目录,因为备份目录一般不经常变动,所以这里写死了



#!/bin/env python  
import os 
import time 
import getpass 
source = [‘/data/mysql‘, ‘/data/mysql/mysql‘]  
target_dir = ‘/backup/‘ 
user = getpass.getuser()  
today = target_dir + time.strftime(‘%Y%m%d‘) 
now = time.strftime(‘%H%M%S‘) 
comment = raw_input(‘please input comment --> ‘)  
if len(comment) == 0: 
    target = today + now + ‘_‘ + user + ‘_‘ + ‘tar.bz2‘  
else:  
    target = today +  now + ‘_‘ + comment + ‘_‘ + user + ‘_‘ + ‘tar.bz2‘  
if not os.path.exists(today):    
    os.mkdir(today)   
    print ‘Create folder successfully‘, today  
else:    
    print today,‘Folder already exists‘  
time.sleep(5) 
zip_command = "tar -cjPf ‘%s‘ %s" % (target, ‘ ‘.join(source))  
if os.system(zip_command) == 0:  
    print ‘ Backup for success:‘, target  
else:  
    print ‘Backup for failed‘ ,target







备注:一下是详细解释:


 

  
#!/bin/env python  
#告诉解释器查找pyton解释器并且使用它 
#_*_encoding:utf8_*_  
#指定编码为utf8编码 
import os 
#导入系统模块  
import time 
#导入时间模块  
import getpass 
#导入获取用户模块  
source = [‘/data/mysql‘, ‘/data/mysql/mysql‘]  
#定义备份源目录 
target_dir = ‘/backup/‘ 
#定义备份目标目录  
user = getpass.getuser() 
#定义使用备份脚本的用户  
today = target_dir + time.strftime(‘%Y%m%d‘) 
#定义今日的日期 
now = time.strftime(‘%H%M%S‘) 
#定义现在的时间  
comment = raw_input(‘please input text --> ‘)  
#定义注释为输入的字符串 
if len(comment) == 0: 
#检查输入的注释是否为空  
    target = today + now + ‘_‘ + user + ‘_‘ + ‘tar.bz2‘  
#如果注释为空,备份文件的文件名为日期时间运行脚本用户  
else:  
    target = today +  now + ‘_‘ + comment + ‘_‘ + user + ‘_‘ + ‘tar.bz2‘  
#如果非空,则使用日期时间注释用户为文件名 
if not os.path.exists(today):  
#检查备份目录下的时间目录是否不存在 
 
    os.mkdir(today)  
#如果不存在创建文件夹 
    print ‘Create folder successfully‘, today  
else:  
#存在,则打印 
    print today,‘Folder already exists‘  
time.sleep(5) 
#暂停五秒  
zip_command = "tar -cjPf ‘%s‘ %s" % (target, ‘ ‘.join(source))  
#定义本备份命令 
 
if os.system(zip_command) == 0:  
#使用系统环境(相当于shell执行备份命令,如果成功返回0) 
    print ‘ 成功备份为:‘, target  
else:  
    print ‘备份失败‘ ,target


本文出自 “清风明月” 博客,请务必保留此出处http://liqingbiao.blog.51cto.com/3044896/1749996

python常用的备份脚本

原文:http://liqingbiao.blog.51cto.com/3044896/1749996

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!