python实现定时自动备份文件到其他主机

定时将源文件或目录使用WinRAR压缩并自动备份到本地或网络上的主机


1.确保WinRAR安装在默认路径或者把WinRAR.exe添加到环境变量中

2.在代码里的sources填写备份的文件或目录,target_dir填写备份目的目录

3.delete_source_file为备份完后是否删除源文件(不删除子文件夹)

4.备份成功/失败后生成备份日志


 

按照格式,填写源目的:

sources = [r'E:\目录1', r'E:\目录2\b.txt'] #例:= [ r'E:\test\1234.txt', r'E:\test1']
target_dir = r'\\10.1.5.227\共享\备份'     #例:= r'D:\备份' 或 = r'\\10.1.5.227\共享目录'
delete_source_file = False                #False/True

手动运行三次,已经有两个备份zip了

打开log查看为什么少了一个

可以看到目录1备份失败了,细看发现,目录1下的a.txt没有权限(读取),是因为用户对该文件没有权限。

如果该目录或者子目录下有一个没有权限,会导致整个目录都不能备份, 日志看到a.txt没有权限.

第二次备份的时候将源文件删除后,第三次备份就没有文件备份了

 

接下来将脚本程序添加到win的计划任务里,就能实现定时自动备份辣<( ̄︶ ̄)>

 

把代码文件添加进来,同时也可以在这里添加参数-d, 指明备份完后删除源文件

 

完整代码

python3.0

  1 # -*- coding=utf-8 -*-
  2 #进行了一场py/etherchannel
  3 import os, sys
  4 import time
  5 import logging
  6 
  7 sources = [r'E:\视频笔记', r'E:\目录\b.txt']  #例:= [ r'E:\test\1234.txt', r'E:\test1']
  8 target_dir = r'\\10.1.5.227\共享\备份'       #例:= r'D:\备份' 或 = r'\\10.1.5.227\共享目录'
  9 delete_source_file = False                  #False/True
 10 
 11 def Init_Logging(path):
 12     logging.basicConfig(level=logging.INFO,  
 13         format='%(asctime)s %(levelname)-8s %(message)s',   
 14         filename=path + '\\' + 'log.txt', 
 15         filemode='a',
 16         datefmt='%Y-%m-%d %X')
 17 
 18 def Ctypes(message, title):
 19     import ctypes
 20     ctypes.windll.user32.MessageBoxA(0,message.encode('gb2312'), \
 21     title.encode('gb2312'),0)
 22     sys.exit()
 23 
 24 def Check_Dir_Permit(dirs, dirc_permit=True, root=''):
 25     for dirc in dirs:
 26         dirc = os.path.join(root,dirc)
 27         try:
 28             os.chdir(dirc)
 29         except IOError as e:
 30             logging.error("找不到指定文件或没有权限  >>> " + str(e))
 31             dirc_permit = False
 32     return dirc_permit
 33     
 34 def Create_Directory(dir):
 35     if not os.path.exists(dir):
 36         try:
 37             os.mkdir(dir)
 38             print('Successfully created directory',dir)
 39         except IOError as e:
 40             Ctypes(u"target_dir 目录路径不存在 ", u' 错误')
 41     assert Check_Dir_Permit([dir]), Ctypes(u"target_dir 没有权限 ", u' 错误')
 42     return dir
 43 
 44 def Check_File_Permit(files, file_permit=True, root=''):
 45     for filename in files:
 46         file = os.path.join(root,filename)
 47         try:
 48             f = open(file)
 49             f.close()
 50         except IOError as e:
 51             logging.error("找不到指定文件或没有权限  >>> " + str(e))
 52             file_permit = False
 53     return file_permit
 54     
 55 def Permit_Source(sources):
 56     allow_sources = []
 57     disallow_sources = []
 58     for source in sources:
 59         file_permit = True
 60         dirc_permit = True
 61         for (root, dirs, files) in os.walk(source):
 62             file_permit = Check_File_Permit(files, file_permit,root=root)
 63             dirc_permit = Check_Dir_Permit(dirs, dirc_permit,root=root)
 64         if os.path.isdir(source) and file_permit and dirc_permit or \
 65             os.path.isfile(source) and Check_File_Permit([source], file_permit):
 66             allow_sources.append(source)
 67         else:
 68             disallow_sources.append(source)
 69     return (allow_sources,disallow_sources)
 70     
 71 def Delete_Files(allow_sources):
 72     for source in allow_sources:
 73         if os.path.isdir(source):
 74             command = 'del /a/s/f/q ' + source    #/s:也把子文件夹的文件一并删除
 75             if os.system(command) == 0:
 76                 logging.info('del: ' + str(source))
 77             else:
 78                 logging.error(str(source) + ' 删除失败')
 79         else:
 80             command = 'del /a/f/q ' + source
 81             if os.system(command) == 0:
 82                 logging.info('del: ' + str(source))
 83             else:
 84                 logging.error(str(source) + ' 删除失败')
 85                 
 86 def Compress_Backup(target, source):
 87     target = target + '\\' + time.strftime('%Y%m%d%H%M%S') + '.rar'
 88     if os.path.exists(r"C:\Program Files (x86)\WinRAR\WinRAR.exe"):
 89         rar_command = r'"C:\Program Files (x86)\WinRAR\WinRAR.exe" A %s %s' % (target,' '.join(source))
 90     else:
 91         rar_command = 'WinRAR' + ' A %s %s' % (target,' '.join(source))
 92     if os.system(rar_command) == 0:  
 93         print('Successful backup to', target)
 94         logging.info(str(source) + ' 备份到 ' + str(target) + ' 成功')
 95         try:
 96             if delete_source_file or sys.argv[1] == '-d':
 97                 Delete_Files(source)
 98         except IndexError:
 99             pass
100     else:
101         logging.error("备份失败:WinRAR出错,确认路径 或 压缩被中断")
102         Ctypes(u"备份失败:WinRAR出错,确认路径 或 压缩被中断", u' 错误')
103 
104 if __name__ == '__main__':
105     target_dir = Create_Directory(target_dir)
106     Init_Logging(target_dir)
107     logging.info('=' * 80)
108     allow_sources, disallow_sources = Permit_Source(sources)
109     if allow_sources:
110         Compress_Backup(target_dir, allow_sources)
111     if disallow_sources:
112         print(disallow_sources, ' 备份失败')
113         logging.error(str(disallow_sources) + ' 备份失败')

 

posted @ 2018-02-23 09:26  lzhh  阅读(987)  评论(0编辑  收藏  举报