国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現定時自動備份文件到其他主機的實例代碼

2020-02-22 23:16:37
字體:
來源:轉載
供稿:網友

定時將源文件或目錄使用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

# -*- coding=utf-8 -*-#進行了一場py/etherchannelimport os, sysimport timeimport loggingsources = [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/Truedef 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_permitdef 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 dirdef 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_permitdef 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) + ' 備份失敗')            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安吉县| 南部县| 桑植县| 额敏县| 新沂市| 安泽县| 嘉义县| 上虞市| 华安县| 临湘市| 凤冈县| 五华县| 镇平县| 讷河市| 深泽县| 尼玛县| 应城市| 大新县| 天镇县| 黄陵县| 桐乡市| 阳江市| 涪陵区| 叶城县| 永昌县| 石楼县| 东源县| 扶绥县| 福鼎市| 北京市| 台南市| 灵台县| 府谷县| 伊川县| 淅川县| 陕西省| 互助| 张掖市| 门头沟区| 延津县| 阳朔县|