使用python备份指定目录并删除备份超过一定时长的文件

 1 #!/usr/bin/env python
 2 #-*- coding: utf-8 -*-
 3 """ 
 4 @Project:Py
 5 @author:
 6 @Email: 
 7 @Software: PyCharm
 8 @file: test_rm.py 
 9 @time: 2018/1/17 0017 下午 14:14 
10 """
11 
12 import os
13 import time
14 
15 # 备份的指定目录
16 source = ['/usr/local/src/test1/']
17 # 备份文件存放路径
18 target_dir='/home/backup/'
19 # 备份时长
20 data = 3
21 # 备份日志
22 filebak_log = "/var/log/filebak.log"
23 # 删除备份文件日志
24 filerm_log = "/var/log/filerm.log"
25 
26 def file_bak():
27     """备份指定目录下的文件"""
28     target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.tar.gz'
29     cmd='tar -zcPf %s %s '%(target,' '.join(source))
30     if os.system(cmd)==0 :
31         with open(filebak_log,'a') as filebak:
32             filebak.write('successfull backup to %s \n' % target)
33 
34 # crontab
35 # 0 4 * * * /usr/bin/python /root/demooil_bak.py >> /var/log/demooil_bak.py.log 2>&1
36 
37 def file_rm():
38     """删除备份目录下超过一定时长的文件"""
39     f = list(os.listdir(target_dir))
40     now_time = time.strftime('%Y%m%d%H%M%S')[0:8]
41     for i in f:
42         if i[15:] == 'tar.gz':
43             exit_time = i[0:8]
44             update_time = int(exit_time) + data
45             if update_time < int(now_time):
46                 os.remove(target_dir+i)
47                 with open(filerm_log,'a') as file_log:
48                     file_log.write("%s删除备份文件%s \n" % (now_time,i))
49 
50 if __name__ == '__main__':
51     file_bak()
52     file_rm()

 

posted @ 2018-01-17 17:36  哈喽哈喽111111  阅读(936)  评论(0编辑  收藏  举报