歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python實例分享:快速查找出被掛馬的文件

Python實例分享:快速查找出被掛馬的文件

日期:2017/3/1 9:35:44   编辑:Linux編程

網站被入侵,擔心被掛馬,因此就想自己寫個腳本來查找那些被掛馬的文件

思路

需要實現准備一份未受感染的源代碼和一份可能受感染的源代碼,然後運行以下腳本,就能找出到底哪些文件被掛馬了。

其中,主要是根據比對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()

腳本執行結果

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved