Python 实现文件的全备份和差异备份详解
Python实现文件的全备份和差异备份
之前有写利用md5方式来做差异备份,但是这种md5方式来写存在以下问题:
- md5sum获取有些软连接的MD5值存在问题
- 不支持对空目录进行备份,因为md5sum无法获取空目录的md5值
- 权限的修改md5sum无法判断
解决方案:
利用文件的mtimectime
mtime(Modifiedtime)是在写入文件时随文件内容的更改而更改的
ctime(Createtime)是在写入文件、更改所有者、权限或链接设置时随Inode的内容更改而更改的
废话不多说直接上代码:
#!/usr/bin/envpython importtime,os,sys,cPickle fileInfo={} deflogger(time,fileName,status,fileNum): f=open('backup.log','a') f.write("%s\t%s\t%s\t\t%s\n"%(time,fileName,status,fileNum)) deftar(sDir,dDir,fileNum): command="tarzcf%s%s>/dev/null2>&1"%(dDir+".tar.gz",sDir) ifos.system(command)==0: logger(time.strftime('%F%X'),dDir+".tar.gz",'success',fileNum) else: logger(time.strftime('%F%X'),dDir+".tar.gz",'failed',fileNum) deffullBak(path): fileNum=0 forroot,dirs,filesinos.walk(path): fornameinfiles: file=os.path.join(root,name) mtime=os.path.getmtime(file) ctime=os.path.getctime(file) fileInfo[file]=(mtime,ctime) fileNum+=1 f=open(P,'w') cPickle.dump(fileInfo,f) f.close() tar(S,D,fileNum) defdiffBak(path): forroot,dirs,filesinos.walk(path): fornameinfiles: file=os.path.join(root,name) mtime=os.path.getmtime(file) ctime=os.path.getctime(file) fileInfo[file]=(mtime,ctime) ifos.path.isfile(P)==0: f=open(P,'w') f.close() ifos.stat(P).st_size==0: f=open(P,'w') cPickle.dump(fileInfo,f) fileNum=len(fileInfo.keys()) f.close() printfileNum tar(S,D,fileNum) else: f=open(P) old_fileInfo=cPickle.load(f) f.close() difference=dict(set(fileInfo.items())^set(old_fileInfo.items())) fileNum=len(difference) printfileNum difference_file=''.join(difference.keys()) printdifference_file tar(difference_file,D,fileNum) f=open(P,'w') cPickle.dump(fileInfo,f) f.close() defUsage(): print''' Syntax:pythonfile_bakcup.pypickle_filemodelsource_dirfilename_bk model:1:Fullbackup2:Differentialbackup example:pythonfile_backup.pyfileinfo.pk2/etcetc_$(date+%F) explain:Automaticallyadd'.tar.gz'suffix ''' sys.exit() iflen(sys.argv)!=5: Usage() P=sys.argv[1] M=int(sys.argv[2]) S=sys.argv[3] D=sys.argv[4] ifM==1: fullBak(S) elifM==2: diffBak(S) else: print"\033[;31mDoesnotsupportthismode\033[0m" Usage()
测试:
$pythonfile_backup.pydata.pk1datadata_$(date+%F)#全备份 $>data/www.linuxeye.com#测试创建文件,修改文件权限 $chmod777data/py/eshop_bk/data.db $pythonfile_backup.pydata.pk2datadata_$(date+%F)_1#备份改变的文件 2 data/py/eshop_bk/data.dbdata/www.linuxeye.com
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!