使用python脚本定时备份web网站
1 #!/usr/bin/env python
2 #-*- coding: utf-8 -*-
3
4 import os
5 import time
6
7 # 备份的指定目录
8 source = ['/data/www/Admin/','/data/www/tpl/']
9 # 备份文件存放路径
10 target_dir='/home/backup/web_back/'
11 # 备份时长
12 data = 5
13 # 备份日志
14 filebak_log = "/var/log/filebak.log"
15 # 删除备份文件日志
16 filerm_log = "/var/log/filerm.log"
17
18 def file_bak():
19 """备份指定目录下的文件"""
20 target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.tar.gz'
21 cmd='tar -zcPf %s %s '%(target,' '.join(source))
22 if os.system(cmd)==0 :
23 with open(filebak_log,'a') as filebak:
24 filebak.write('successfull backup to %s \n' % target)
25
30 def file_rm():
31 """删除备份目录下超过一定时长的文件"""
32 f = list(os.listdir(target_dir))
33 now_time = time.strftime('%Y%m%d%H%M%S')[0:8]
34 for i in f:
35 if i[15:] == 'tar.gz':
36 exit_time = i[0:8]
37 update_time = int(exit_time) + data
38 if update_time < int(now_time):
39 os.remove(target_dir+i)
40 with open(filerm_log,'a') as file_log:
41 file_log.write("%s删除备份文件%s \n" % (now_time,i))
42
43 if __name__ == '__main__':
44 file_bak()
45 file_rm()
# linux定时执行python文件
# crontab -e 添加如下信息:
# 0 4 * * * /usr/bin/python /root/bak.py >> /var/log/bak.py.log 2>&1