python核心程式設計:web伺服器日誌分析簡單指令碼

pythontab發表於2013-03-15

由於N種原因,一個分析入侵日誌的任務落在了我身上,1G的日誌,怎麼去快速分析呢??刺總說可以搞個指令碼解析入庫,再到資料庫分析。。。算了,那就蛋疼了,直接碼個指令碼把有問題的日誌拿出來分析吧。於是就有了這個小指令碼。至於怎麼用就要看你自己了,哈哈,比如查到sql注入語句,然後看到IP,就可以改下指令碼,用IP為特徵取出日誌,分析入侵過程。速度很快哦,我那破機器,跑1G日誌檔案也就幾秒鐘的啦。

在工作中寫程式完成任務是很快樂的事,也很有意思。哈哈

使用引數:seay.py E:/1.log

#coding = utf8
#Filename = seay.py
import os
import sys
 
#特徵,可以隨意改,兩塊五一次
_tezheng = {'union','select','file_put_contents'}
 
def CheckFile(_path):
     
    _f = open(_path,"r")
    _All_Line = _f.readlines() 
    _f.close()
     
    _Count_Line =0
    _Len_Line = len(_All_Line)
         
    _Ex_Str = ''
 
    print('Read Over --')
     
    while _Count_Line<_Len_Line:
            _Str = _All_Line[_Count_Line]            
            for _tz_Str in _tezheng:
                if _tz_Str in _Str: #可以加and條件,這個貴一點,5毛一次
                    _Ex_Str+=_tz_Str+_Str+'\r\n'
            _Count_Line+=1
     
    _f1 = open(_path+'.seay.txt',"w")
    _f1.write(_Ex_Str)
    _f1.close()    
    print 'Find Over--'   
 
if len(sys.argv)==2:
    _File = sys.argv[1]
    if os.path.lexists(_File):
        CheckFile(_File)
    else:
        print('File does not exist!')
else:
    print 'Parameter error'
    print sys.argv[0]+' FilePath'


最終生成一個檔案為:原檔名.seay.txt在同目錄下,格式為匹配的特徵+日誌


相關文章