Python執行個體分享:快速尋找出被掛馬的檔案

來源:互聯網
上載者:User
思路

需要實現準備一份未受感染的原始碼和一份可能受感染的原始碼,然後運行以下指令碼,就能找出到底哪些檔案被掛馬了。

其中,主要是根據比對2份檔案的md5值來過濾可能被掛馬的檔案(確切的說應該是被修改過的檔案)

Python指令碼

複製代碼 代碼如下:


__author__ = 'Flying'
#coding:utf-8
#Date:2014.6.5
#檢測修改過的檔案
import os,sys,hashlib,datetime
global_DirOld = ""
global_DirNew = ""
global_FilesList = []
#輸入要比對的檔案路徑
def InputDirPath():
global global_DirOld,global_DirNew
global_DirOld = unicode(raw_input("請輸入備份檔案所在目錄:"),"utf-8")
while not os.path.exists(global_DirOld):
print u"指定的路徑不存在,請重新輸入"
global_DirOld = unicode(raw_input("請輸入備份檔案所在目錄:"),"utf-8")
global_DirNew = unicode(raw_input("請輸入要檢測檔案的目錄:"),"utf-8")
while not os.path.exists(global_DirNew):
print u"指定的路徑不存在,請重新輸入"
global_DirNew = unicode(raw_input("請輸入要檢測檔案的目錄:"),"utf-8")

#將資料儲存到檔案中
def SaveToFile(filePath,content):
try:
f = open(filePath,"a+")
f.write(content.encode("utf-8") + "\n")
f.close()
except Exception,ex:
print "Error:" + str(ex)

#計算檔案的MD5值
def CalcMD5(filepath):
try:
#以二進位的形式開啟
with open(filepath,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash
except Exception,ex:
print "Error:" + str(ex)
return None

#遍曆目錄下的所有檔案
def GetAllSubFiles():
global global_FilesList
for dir in os.walk(global_DirNew):
for file in dir[2]:
filePath = dir[0] + os.sep + file
global_FilesList.append(filePath[len(global_DirNew)+1:])

#列出新增檔案和變動的檔案
def ListChangedFiles():
global global_DirOld,global_DirNew,global_FilesList
print u"變動或新增的檔案:"
for file in global_FilesList:
filePathOld = global_DirOld + os.sep + file
filePathNew = global_DirNew + os.sep + file
if not os.path.exists(filePathOld) or CalcMD5(filePathOld)!=CalcMD5(filePathNew):
content = "[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+ "]" + filePathNew
print content
SaveToFile("ChangedFiles.txt",content)

if __name__=="__main__":
InputDirPath()
GetAllSubFiles()
ListChangedFiles()

指令碼執行結果

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.