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单例模式实例分析
Jan 14 Python
使用Python脚本对Linux服务器进行监控的教程
Apr 02 Python
Django框架中方法的访问和查找
Jul 15 Python
用不到50行的Python代码构建最小的区块链
Nov 16 Python
用python实现的线程池实例代码
Jan 06 Python
flask中过滤器的使用详解
Aug 01 Python
Python基于matplotlib画箱体图检验异常值操作示例【附xls数据文件下载】
Jan 07 Python
在pytorch中对非叶节点的变量计算梯度实例
Jan 10 Python
利用PyQt中的QThread类实现多线程
Feb 18 Python
python中id函数运行方式
Jul 03 Python
python实现图像外边界跟踪操作
Jul 13 Python
python四个坐标点对图片区域最小外接矩形进行裁剪
Jun 04 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教程之phpize使用方法
2014/02/12 PHP
php过滤html标记属性类用法实例
2014/09/23 PHP
thinkphp ajaxfileupload实现异步上传图片的示例
2017/08/28 PHP
PHP 爬取网页的主要方法
2018/07/13 PHP
php无限极分类实现方法分析
2019/07/04 PHP
斜45度寻路实现函数
2009/08/20 Javascript
js的.innerHTML = &quot;&quot;IE9下显示有错误的解决方法
2013/09/16 Javascript
node.js中的querystring.parse方法使用说明
2014/12/10 Javascript
javascript实现的图片切割多块效果实例
2015/05/07 Javascript
jQuery+php实时获取及响应文本框输入内容的方法
2016/05/24 Javascript
Javascript中常用的检测方法小结
2016/10/08 Javascript
浅谈Vue网络请求之interceptors实际应用
2018/02/28 Javascript
从vue源码解析Vue.set()和this.$set()
2018/08/30 Javascript
详解JSON和JSONP劫持以及解决方法
2019/03/08 Javascript
Vue路由前后端设计总结
2019/08/06 Javascript
uni-app 支持多端第三方地图定位的方法
2020/01/03 Javascript
原生js实现九宫格拖拽换位
2021/01/26 Javascript
[02:19]2018年度DOTA2最佳核心位选手-完美盛典
2018/12/17 DOTA
python中关于日期时间处理的问答集锦
2013/03/08 Python
Python中使用scapy模拟数据包实现arp攻击、dns放大攻击例子
2014/10/23 Python
使用Python标准库中的wave模块绘制乐谱的简单教程
2015/03/30 Python
Python中MySQL数据迁移到MongoDB脚本的方法
2016/04/28 Python
在Python中使用Neo4j的方法
2019/03/14 Python
python 引用传递和值传递详解(实参,形参)
2020/06/05 Python
中国综合性网上购物商城:当当(网上卖书起家)
2016/11/16 全球购物
韩国演唱会订票网站:StubHub韩国
2019/01/17 全球购物
学年末自我鉴定
2014/01/21 职场文书
公司中层干部的自我评价分享
2014/03/01 职场文书
制药工程专业职业生涯规划范文
2014/03/10 职场文书
考核工作实施方案
2014/03/30 职场文书
英文感谢信范文
2015/01/21 职场文书
导游词之吉林花园山
2019/10/17 职场文书
js 数组 fill() 填充方法
2021/11/02 Javascript
nginx从安装到配置详细说明(安装,安全配置,防盗链,动静分离,配置 HTTPS,性能优化)
2022/02/12 Servers
人民币符号
2022/02/17 杂记
JavaWeb Servlet开发注册页面实例
2022/04/11 Java/Android