python指令碼實現檔案備份

2021-09-28 15:48:26 字數 2024 閱讀 6978

本指令碼通過判斷是否為周一來執行完全備份或增量備份,需提前放到計畫任務中每天執行,實現周一完全備份,之後每天增量備份的功能.具體**實現如下

#!/root/bin/python

from time import strftime

import os

import tarfile

import hashlib

import pickle

def check_md5(fname):

m = hashlib.md5(

) with open(fname,

'rb'

) as fobj:

while 1:

data = fobj.read(4096)

if not data:

break

m.update(

data

)return m.hexdigest(

)def full_backup(src,dst,md5file):

fname = os.path.basename(src)

fname = '%s_full_%s.tar.gz'

%(fname,strftime(

'%y%m%d'))

fname = os.path.join(dst,fname)

tar = tarfile.open(fname,

'w:gz'

) tar.add(src)

tar.close(

) md5dict =

for path,folders,files in os.walk(src):

for file in files:

key = os.path.join(path,file)

md5dict[key] = check_md5(key)

with open(md5file,

'wb'

) as fobj:

pickle.dump(md5dict,fobj)

def incr_backup(src,dst,md5file):

fname = os.path.basename(src)

fname = '%s_incr_%s.tar.gz'

%(fname,strftime(

'%y%m%d'))

fname = os.path.join(dst,fname)

md5dict =

for path,folders,files in os.walk(src):

for file in files:

key = os.path.join(path,file)

md5dict[key] = check_md5(key)

with open(md5file,

'rb'

) as fobj:

old_md5 = pickle.load(fobj)

tar = tarfile.open(fname,

'w:gz'

)for key in md5dict:

if old_md5.get(key)

!= md5dict[key]:

tar.add(key)

tar.close(

) with open(md5file,

'wb'

) as fobj:

pickle.dump(md5dict,fobj)

if __name__ == '__main__':

src = '/tmp/demo/security'

dst = '/tmp/demo/backup'

md5file = '/tmp/demo/backup/md5.data'

if strftime(

'%a'

) == 'mon':

full_backup(src,dst,md5file)

else:

incr_backup(src,dst,md5file)

python 備份檔案指令碼

usr bin env python filename backup ver1.pyimport os import time source r d python test r d python test1 target dir d python test2 remember to change t...

linux指令碼實現備份檔案

要求 編寫乙個指令碼實現備份 var log目錄下的所有檔案到 bak目錄下,要求檔名是包含當天日期,精確到秒,檔名例如 2019 6 6 2 30 20 log.tar.gz。同時要求刪除 bak目錄下七天前的備份檔案,只保留最近7天的 bin bash 獲得當前的時間 ctime date y ...

PYTHON備份指令碼

usr local python251 bin python import sysimport osimport time 如果沒有輸入引數,則會提示並且中斷。iflen sys ar 1 0 print please input source file or directory.sys exit ...