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


Posted in Python onFebruary 23, 2018

定时将源文件或目录使用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了

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

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

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

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

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

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

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

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

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

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

完整代码

python3.0

# -*- coding=utf-8 -*-
#进行了一场py/etherchannel
import os, sys
import time
import logging
sources = [r'E:\视频笔记', r'E:\目录\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
def Init_Logging(path):
  logging.basicConfig(level=logging.INFO, 
    format='%(asctime)s %(levelname)-8s %(message)s',  
    filename=path + '\\' + 'log.txt', 
    filemode='a',
    datefmt='%Y-%m-%d %X')
def Ctypes(message, title):
  import ctypes
  ctypes.windll.user32.MessageBoxA(0,message.encode('gb2312'), \
  title.encode('gb2312'),0)
  sys.exit()
def Check_Dir_Permit(dirs, dirc_permit=True, root=''):
  for dirc in dirs:
    dirc = os.path.join(root,dirc)
    try:
      os.chdir(dirc)
    except IOError as e:
      logging.error("找不到指定文件或没有权限 >>> " + str(e))
      dirc_permit = False
  return dirc_permit
def Create_Directory(dir):
  if not os.path.exists(dir):
    try:
      os.mkdir(dir)
      print('Successfully created directory',dir)
    except IOError as e:
      Ctypes(u"target_dir 目录路径不存在 ", u' 错误')
  assert Check_Dir_Permit([dir]), Ctypes(u"target_dir 没有权限 ", u' 错误')
  return dir
def Check_File_Permit(files, file_permit=True, root=''):
  for filename in files:
    file = os.path.join(root,filename)
    try:
      f = open(file)
      f.close()
    except IOError as e:
      logging.error("找不到指定文件或没有权限 >>> " + str(e))
      file_permit = False
  return file_permit
def Permit_Source(sources):
  allow_sources = []
  disallow_sources = []
  for source in sources:
    file_permit = True
    dirc_permit = True
    for (root, dirs, files) in os.walk(source):
      file_permit = Check_File_Permit(files, file_permit,root=root)
      dirc_permit = Check_Dir_Permit(dirs, dirc_permit,root=root)
    if os.path.isdir(source) and file_permit and dirc_permit or \
      os.path.isfile(source) and Check_File_Permit([source], file_permit):
      allow_sources.append(source)
    else:
      disallow_sources.append(source)
  return (allow_sources,disallow_sources)
def Delete_Files(allow_sources):
  for source in allow_sources:
    if os.path.isdir(source):
      command = 'del /a/s/f/q ' + source  #/s:也把子文件夹的文件一并删除
      if os.system(command) == 0:
        logging.info('del: ' + str(source))
      else:
        logging.error(str(source) + ' 删除失败')
    else:
      command = 'del /a/f/q ' + source
      if os.system(command) == 0:
        logging.info('del: ' + str(source))
      else:
        logging.error(str(source) + ' 删除失败')
def Compress_Backup(target, source):
  target = target + '\\' + time.strftime('%Y%m%d%H%M%S') + '.rar'
  if os.path.exists(r"C:\Program Files (x86)\WinRAR\WinRAR.exe"):
    rar_command = r'"C:\Program Files (x86)\WinRAR\WinRAR.exe" A %s %s' % (target,' '.join(source)) #WinRAR.exe" A %s %s -r'加上-r是作用到子文件夹中同名的文件
  else:
    rar_command = 'WinRAR' + ' A %s %s' % (target,' '.join(source))
  if os.system(rar_command) == 0: 
    print('Successful backup to', target)
    logging.info(str(source) + ' 备份到 ' + str(target) + ' 成功')
    try:
      if delete_source_file or sys.argv[1] == '-d':
        Delete_Files(source)
    except IndexError:
      pass
  else:
    logging.error("备份失败:WinRAR出错,确认路径 或 压缩被中断")
    Ctypes(u"备份失败:WinRAR出错,确认路径 或 压缩被中断", u' 错误')
if __name__ == '__main__':
  target_dir = Create_Directory(target_dir)
  Init_Logging(target_dir)
  logging.info('=' * 80)
  allow_sources, disallow_sources = Permit_Source(sources)
  if allow_sources:
    Compress_Backup(target_dir, allow_sources)
  if disallow_sources:
    print(disallow_sources, ' 备份失败')
    logging.error(str(disallow_sources) + ' 备份失败')

总结

以上所述是小编给大家介绍的python实现定时自动备份文件到其他主机的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python实现的二叉树算法和kmp算法实例
Apr 25 Python
在Python的框架中为MySQL实现restful接口的教程
Apr 08 Python
python optparse模块使用实例
Apr 09 Python
python分块读取大数据,避免内存不足的方法
Dec 10 Python
python中logging模块的一些简单用法的使用
Feb 22 Python
Scrapy-Redis结合POST请求获取数据的方法示例
May 07 Python
QML使用Python的函数过程解析
Sep 26 Python
Python搭建代理IP池实现存储IP的方法
Oct 27 Python
浅析python表达式4+0.5值的数据类型
Feb 26 Python
pandas将list数据拆分成行或列的实现
Dec 13 Python
python中的插入排序的简单用法
Jan 19 Python
python如何读取和存储dict()与.json格式文件
Jun 25 Python
Python机器学习算法之k均值聚类(k-means)
Feb 23 #Python
python3调用R的示例代码
Feb 23 #Python
python中kmeans聚类实现代码
Feb 23 #Python
python实现SOM算法
Feb 23 #Python
python实现k-means聚类算法
Feb 23 #Python
python写一个md5解密器示例
Feb 23 #Python
Python机器学习之K-Means聚类实现详解
Feb 22 #Python
You might like
无数据库的详细域名查询程序PHP版(3)
2006/10/09 PHP
页面乱码问题的根源及其分析
2013/08/09 PHP
Laravel框架分页实现方法分析
2018/06/12 PHP
ExtJS的FieldSet的column列布局
2009/11/20 Javascript
jQuery 幻灯片插件(带缩略图功能)
2011/01/24 Javascript
关于jQuery的inArray 方法介绍
2011/10/08 Javascript
20款效果非常棒的 jQuery 插件小结分享
2011/11/18 Javascript
javascript实现des解密加密全过程
2014/04/03 Javascript
jQuery手机浏览器中拖拽动作的艰难性分析
2015/02/04 Javascript
jquery动态改变div宽度和高度
2015/02/09 Javascript
浅谈Node.js:Buffer模块
2016/12/05 Javascript
微信小程序 数据遍历的实现
2017/04/05 Javascript
ionic中的$ionicPlatform.ready事件中的通用设置
2017/06/11 Javascript
jQuery dateRangePicker插件使用方法详解
2017/07/28 jQuery
nodejs实现截取上传视频中一帧作为预览图片
2017/12/10 NodeJs
js JSON.stringify()基础详解
2019/06/19 Javascript
vue-cli2与vue-cli3在一台电脑共存的实现方法
2019/09/25 Javascript
详解vue中多个有顺序要求的异步操作处理
2019/10/29 Javascript
[03:12]2016完美“圣”典风云人物:单车专访
2016/12/02 DOTA
python通过opencv实现批量剪切图片
2017/11/13 Python
Python补齐字符串长度的实例
2018/11/15 Python
pandas通过索引进行排序的示例
2018/11/16 Python
python实现定时压缩指定文件夹发送邮件
2020/12/22 Python
Python应用领域和就业形势分析总结
2019/05/14 Python
python跳出双层for循环的解决方法
2019/06/24 Python
python不到50行代码完成了多张excel合并的实现示例
2020/05/28 Python
切尔西足球俱乐部官方网上商店:Chelsea FC
2019/06/17 全球购物
进修护士自我鉴定
2013/10/14 职场文书
乡村文明行动实施方案
2014/03/29 职场文书
合作经营协议书范本
2014/04/17 职场文书
公务员诚信承诺书
2014/05/26 职场文书
飞机制造技术专业求职信
2014/07/27 职场文书
学习普通话的体会
2014/11/07 职场文书
杨善洲电影观后感
2015/06/04 职场文书
大学生读书笔记范文
2015/07/01 职场文书
浅谈Python 中的复数问题
2021/05/19 Python