python實(shí)現(xiàn)定時(shí)自動(dòng)備份文件到其他主機(jī)的實(shí)例代碼
定時(shí)將源文件或目錄使用WinRAR壓縮并自動(dòng)備份到本地或網(wǎng)絡(luò)上的主機(jī)
1.確保WinRAR安裝在默認(rèn)路徑或者把WinRAR.exe添加到環(huán)境變量中
2.在代碼里的sources填寫(xiě)備份的文件或目錄,target_dir填寫(xiě)備份目的目錄
3.delete_source_file為備份完后是否刪除源文件(不刪除子文件夾)
4.備份成功/失敗后生成備份日志
按照格式,填寫(xiě)源目的:
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
手動(dòng)運(yùn)行三次,已經(jīng)有兩個(gè)備份zip了
打開(kāi)log查看為什么少了一個(gè)
可以看到目錄1備份失敗了,細(xì)看發(fā)現(xiàn),目錄1下的a.txt沒(méi)有權(quán)限(讀取),是因?yàn)橛脩魧?duì)該文件沒(méi)有權(quán)限。
如果該目錄或者子目錄下有一個(gè)沒(méi)有權(quán)限,會(huì)導(dǎo)致整個(gè)目錄都不能備份, 日志看到a.txt沒(méi)有權(quán)限.
第二次備份的時(shí)候?qū)⒃次募h除后,第三次備份就沒(méi)有文件備份了
接下來(lái)將腳本程序添加到win的計(jì)劃任務(wù)里,就能實(shí)現(xiàn)定時(shí)自動(dòng)備份辣<( ̄︶ ̄)>
把代碼文件添加進(jìn)來(lái),同時(shí)也可以在這里添加參數(shù)-d, 指明備份完后刪除源文件
完整代碼
python3.0
# -*- coding=utf-8 -*- #進(jìn)行了一場(chǎng)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("找不到指定文件或沒(méi)有權(quán)限 >>> " + 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' 錯(cuò)誤') assert Check_Dir_Permit([dir]), Ctypes(u"target_dir 沒(méi)有權(quán)限 ", u' 錯(cuò)誤') 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("找不到指定文件或沒(méi)有權(quán)限 >>> " + 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出錯(cuò),確認(rèn)路徑 或 壓縮被中斷") Ctypes(u"備份失敗:WinRAR出錯(cuò),確認(rèn)路徑 或 壓縮被中斷", u' 錯(cuò)誤') 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) + ' 備份失敗')
總結(jié)
以上所述是小編給大家介紹的python實(shí)現(xiàn)定時(shí)自動(dòng)備份文件到其他主機(jī)的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
python django 實(shí)現(xiàn)驗(yàn)證碼的功能實(shí)例代碼
本篇文章主要介紹了python django 實(shí)現(xiàn)驗(yàn)證碼的功能實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05python下os模塊強(qiáng)大的重命名方法renames詳解
這篇文章主要介紹了python下os模塊強(qiáng)大的重命名方法renames詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03詳解pandas映射與數(shù)據(jù)轉(zhuǎn)換
這篇文章主要介紹了pandas映射與數(shù)據(jù)轉(zhuǎn)換的相關(guān)資料,幫助大家更好的利用python進(jìn)行數(shù)據(jù)分析,感興趣的朋友可以了解下2021-01-01PyMongo進(jìn)行MongoDB查詢和插入操作的高效使用示例
這篇文章主要為大家介紹了PyMongo進(jìn)行MongoDB查詢和插入操作的高效使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11python 實(shí)現(xiàn)在一張圖中繪制一個(gè)小的子圖方法
今天小編就為大家分享一篇python 實(shí)現(xiàn)在一張圖中繪制一個(gè)小的子圖方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07淺談Selenium+Webdriver 常用的元素定位方式
這篇文章主要介紹了淺談Selenium+Webdriver 常用的元素定位方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01TensorFlow人工智能學(xué)習(xí)Keras高層接口應(yīng)用示例
這篇文章主要為大家介紹了TensorFlow人工智能學(xué)習(xí)中Keras高層接口的應(yīng)用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11