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 相关文章推荐
Linux下Python获取IP地址的代码
Nov 30 Python
Python Sql数据库增删改查操作简单封装
Apr 18 Python
Django自定义插件实现网站登录验证码功能
Apr 19 Python
Python2.X/Python3.X中urllib库区别讲解
Dec 19 Python
Python数据可视化教程之Matplotlib实现各种图表实例
Jan 13 Python
浅谈python之高阶函数和匿名函数
Mar 21 Python
Python绘制堆叠柱状图的实例
Jul 09 Python
详解python中的模块及包导入
Aug 30 Python
Python数据持久化存储实现方法分析
Dec 21 Python
Python通过Tesseract库实现文字识别
Mar 05 Python
pytorch 中autograd.grad()函数的用法说明
May 12 Python
浅谈哪个Python库才最适合做数据可视化
Jun 28 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
Notice: Trying to get property of non-object problem(PHP)解决办法
2012/03/11 PHP
如何使用php判断所处服务器操作系统的类型
2013/06/20 PHP
php实现的简单日志写入函数
2015/03/31 PHP
php异常处理方法实例汇总
2015/06/24 PHP
1亿条数据如何分表100张到Mysql数据库中(PHP)
2015/07/29 PHP
laravel通过a标签从视图向控制器实现传值
2019/10/15 PHP
JQuery index()方法使用代码
2010/06/02 Javascript
jQuery EasyUI API 中文文档 - NumberSpinner数值微调器使用介绍
2011/10/21 Javascript
用jquery统计子菜单的条数示例代码
2013/10/18 Javascript
关于jquery中全局函数each使用介绍
2013/12/10 Javascript
使用javascript实现监控视频播放并打印日志
2015/01/05 Javascript
DOM基础教程之使用DOM
2015/01/19 Javascript
javascript中数组的定义及使用实例
2015/01/21 Javascript
JS继承用法实例分析
2015/02/05 Javascript
使用jQuery实现更改默认alert框体
2015/04/13 Javascript
Hammer.js+轮播原理实现简洁的滑屏功能
2016/02/02 Javascript
js中小数向上取整数,向下取整数,四舍五入取整数的实现(必看篇)
2017/02/13 Javascript
vue devtools的安装与使用教程
2018/08/08 Javascript
vue服务端渲染页面缓存和组件缓存的实例详解
2018/09/18 Javascript
微信小程序实现签到弹窗动画
2020/09/21 Javascript
全网小程序接口请求封装实例代码
2020/11/06 Javascript
Python 网页解析HTMLParse的实例详解
2017/08/10 Python
Python smtplib实现发送邮件功能
2018/05/22 Python
Python文件读写常见用法总结
2019/02/22 Python
OpenCV-Python 摄像头实时检测人脸代码实例
2019/04/30 Python
Django应用程序入口WSGIHandler源码解析
2019/08/05 Python
python异常处理之try finally不报错的原因
2020/05/18 Python
Python中的整除和取模实例
2020/06/03 Python
家长给老师的道歉信
2014/01/13 职场文书
餐饮管理自我介绍信
2014/01/15 职场文书
英语教研活动总结
2014/07/02 职场文书
经理岗位职责
2015/02/02 职场文书
个人维稳承诺书
2015/05/04 职场文书
2015年控辍保学工作总结
2015/05/18 职场文书
Vue CLI中模式与环境变量的深入详解
2021/05/30 Vue.js
前端JavaScript大管家 package.json
2021/11/02 Javascript