python实现文件快照加密保护的方法

本文实例讲述了python实现文件快照加密保护的方法。分享给大家供大家参考。具体如下:

这段代码可以对指定的目录进行扫描,包含子目录,对指定扩展名的文件进行sha-1加密后存储在cvs文件,以防止文件被篡改

调用方法:python snapper.py > todaycheck.csv

# hello, this is a script written in python. see http://www.pyhon.org
#
# snapper 1.2p
#
# this script will walk a directory (and its subdirectories) and compute
# sha (secure hash algorithm) for specific files (according to their
# extensions) and ouput a csv file (suited for loading into a spreadsheet
# editor,a database or simply comparing with diff or examdiff.).
#
# you can redirect the output of this script to a file.
# eg. python snapper.py > todaycheck.csv
#
# this script can be usefull to check system files tampering.
#
# this script is public domain. feel free to reuse it.
# the author is:
# sebastien sauvage
#
# http://sebsauvage.net
#
# more quick & dirty scripts are available at http://sebsauvage.net/python/
#
# directory to scan and extensions are hardcoded below:
directorystart = r’c:\windows’
extensionlist=[‘.exe’,’.dll’,’.ini’,’.ocx’,’.cpl’,’.vxd’,’.drv’,’.vbx’,’.com’,’.bat’,’.src’,
‘.sys’,’.386′,’.acm’,’.ax’, ‘.bpl’,’.bin’,’.cab’,’.olb’,’.mpd’,’.pdr’,’.jar’]
import os,string,sha,stat,sys
def snapper ( directorystart , extensionlist ) :
os.path.walk( directorystart, snapper_callback, extensionlist )
def snapper_callback ( extensionlist , directory, files ) :
sys.stderr.write(‘scanning ‘+directory+’\n’)
for filename in files:
if os.path.isfile( os.path.join(directory,filename) ) :
if string.lower(os.path.splitext(filename)[1]) in extensionlist :
filelist.append(filesha ( os.path.join(directory,filename) ))
def filesha ( filepath ) :
sys.stderr.write(‘ reading ‘+os.path.split(filepath)[1]+’\n’)
file = open(filepath,’rb’)
digest = sha.new()
data = file.read(65536)
while len(data) != 0:
digest.update(data)
data = file.read(65536)
file.close()
return ‘”‘+filepath+'”,’+str(os.stat(filepath)[6])+’,”‘+digest.hexdigest()+'”‘
sys.stderr.write(‘snapper 1.1p – http://sebsauvage.net/python/\n’)
filelist = []
snapper( directorystart , extensionlist )
sys.stderr.write(‘sorting…\n’)
filelist.sort()
filelist.insert(0, ‘”file path”,”file size”,”sha”‘ )
sys.stderr.write(‘printing…\n’)
for line in filelist:
print line
sys.stderr.write(‘all done.\n’)

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论