生活随笔
收集整理的這篇文章主要介紹了
备份程序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、既要可以實現完全備份,又要實現增量備份
2、完全備份時,將目錄打個tar包,計算每個文件的md5值
3、增量備份時,備份有變化的文件和新增加的文件,更新md5值
import time
import os
import tarfile
import hashlib
import pickledef check_md5(fname):m =
hashlib.md5()with open(fname, 'rb') as fobj:while True:data = fobj.read(4096
)if not data:breakm.update(data)return m.hexdigest()def full_backup(src_dir, dst_dir, md5file):fname = os.path.basename(src_dir.rstrip(
'/'))fname =
'%s_full_%s.tar.gz' % (fname, time.strftime(
'%Y%m%d'))fname =
os.path.join(dst_dir, fname)md5dict =
{}tar = tarfile.open(fname,
'w:gz')tar.add(src_dir)tar.close()for path, folders, files
in os.walk(src_dir):for each_file
in files:key =
os.path.join(path, each_file)md5dict[key] =
check_md5(key)with open(md5file, 'wb') as fobj:pickle.dump(md5dict, fobj)def incr_backup(src_dir, dst_dir, md5file):fname = os.path.basename(src_dir.rstrip(
'/'))fname =
'%s_incr_%s.tar.gz' % (fname, time.strftime(
'%Y%m%d'))fname =
os.path.join(dst_dir, fname)md5dict =
{}with open(md5file, 'rb') as fobj:oldmd5 =
pickle.load(fobj)for path, folders, files
in os.walk(src_dir):for each_file
in files:key =
os.path.join(path, each_file)md5dict[key] =
check_md5(key)with open(md5file, 'wb') as fobj:pickle.dump(md5dict, fobj)tar = tarfile.open(fname,
'w:gz')for key
in md5dict:if oldmd5.get(key) !=
md5dict[key]:tar.add(key)tar.close()if __name__ ==
'__main__':# mkdir /tmp/demo; cp -r /etc/security /tmp/demosrc_dir =
'/tmp/demo/security'dst_dir =
'/var/tmp/backup' # mkdir /var/tmp/backupmd5file =
'/var/tmp/backup/md5.data'if time.strftime(
'%a') ==
'Mon':full_backup(src_dir, dst_dir, md5file)else:incr_backup(src_dir, dst_dir, md5file) ?
轉載于:https://www.cnblogs.com/lsgo/p/10603453.html
總結
以上是生活随笔為你收集整理的备份程序的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。