用于日志分析分析日志文件
應急響應工具-日志分析
rizhi_find.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import requests
from retrying import retry
import os
from collections import Counter
# 需要分析的日志名稱
# print dir(rizhifenxi_auto)
# 1、打開日志文件,將需要分析的日志保存log目錄下
def open_file():
fpath = os.getcwd() + "/log/"
files = os.listdir(fpath)
for f in files:
for f in files: #
if os.path.isfile(fpath + f):
fhandle = open(fpath + f, 'r')
aa = fhandle.readlines()
return aa,len(aa)
file,count=open_file()
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko','Accept': 'text/html, application/xhtml+xml, image/jxr, */*','Accept-Language': 'zh-CN','Connection': 'close'}
# 輸出結果保存在result目錄下
def save_path():
path = os.getcwd() + "/result/"
if not os.path.exists(path):
os.makedirs(path)
else:
pass
return path
weicha_ip=list()
guowai_ip=set()
ip_address = list()
path = save_path()
yichang_ip = list()
guowai_ip_lianjie = open(path + "guowai_ip_lianjie.txt", "w")
# 在進行ip地址歸屬地查詢過程中,可能由于查詢歸屬地接口的原因,造成ip歸屬地查詢失敗,查詢未成功的ip地址會保存在shibai_ip.txt中
@retry(stop_max_attempt_number=3)
def check_ip(dizhi):
URL='http://ip-api.com/json/'+dizhi+'?lang=zh-CN'
# try:
r = requests.get(URL, timeout=3,headers=headers)
json_data = r.json()
if json_data[u'status'] == 'success':
country = json_data[u'country'].encode('utf-8')
provice=json_data[u'regionName'].encode('utf-8')
city = json_data[u'city'].encode('utf-8')
if country not in "中國":
guowai_ip.add(dizhi)
aa= country,provice,city
# print aa
return aa
# except :
# yichang_ip.append(dizhi)
ip_list=list()
# 1、提取日志中ip地址
def ip_tiqu():
for i in file:
ip=re.findall(r'\d+.\d+.\d+.\d+', i.strip())
ip_list.append(ip[0])
return ip_list
# 2、對提取到的ip地址進行頻率統計,并判斷相關地址歸屬地
def ip_guishudi():
ip_tiqu()
result = Counter(ip_list)
result1 = dict(result)
res = sorted(result1.items(), key=lambda d: d[1], reverse=True)
for i in range(len(res)):
# print len (res);
ip=res[i][0];
if res[i][1]>20:
try:
bb=check_ip(dizhi=ip);
result= i,ip,bb,res[i][1]
ip_address.append(result)
except:
result = i, ip, '查詢失敗', res[i][1]
ip_address.append(result)
return ip_address
# 4、根據輸入的關鍵字進行搜索,支持最多兩個關鍵字同時查找
def find_str():
find_result=open(path+"find_result.txt","w")
canshu1,canshu2,dingzhi=raw_input("please input keywords1:").split(',')
# print len(canshu2)
if len(canshu1)>0 and len(canshu2)==0 and len(dingzhi)==0:
for i in file:
if canshu1 in i:
# print i.strip()
find_result.write(i.strip()+'\n')
elif len(canshu1)>0 and len(canshu2)>0 and dingzhi is str(1):
for i in file:
if canshu1 in i.strip() and canshu2 in i.strip():
print i.strip()
find_result.write(i.strip() + '\n')
elif len(canshu1)>0 and len(canshu2)>0 and dingzhi is str(2):
for i in file:
if canshu1 in i or canshu2 in i:
# print i.strip()
find_result.write(i.strip() + '\n')
else:
print "type error,please check your input"
find_result.close()
# 5、對查找到的結果進行ip地址提取,將提取結果保存在列表ip1中
fenxi_result=open(path+"find_result.txt","r").readlines()
for i1 in fenxi_result:
ip = re.findall(r'\d+.\d+.\d+.\d+', i1.strip())[0]
ip1.add(ip)
return ip1
# 6、查看ip1中的地址列表還訪問過哪些url,并將結果保存在log.txt中
def url_tongji():
log=open(path+"log.txt","w")
for ip in find_str():
# print ip
for i in file:
if ip in i.strip() :
if str(200) or str(500) in i.strip():
# print i.strip()
log.write(i.strip()+'\n')
# 7、篩選國外ip訪問過的鏈接
def guowai_lianjie():
for i in guowai_ip:
for i in file:
for i1 in guowai_ip:
if i1 in i and i.split(' ')[8] in "200":
print i1.strip
guowai_ip_lianjie.write(i.strip()+'\n')
if __name__=='__main__':
ip1=set()
ip_list=list()
# find_str()
url_tongji()
print "請在"+path+"文件夾下查看相關結果"
rizhifenxi.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 對日志中的訪問路徑進行匯總,根據數量進行排名,并將訪問量前20的統計情況輸出保存到表格中。
import xlwt
import re
from collections import Counter
import os
import rizhi_find
# _*_coding:utf-8_*_
url_list = list()
bb = list()
# 2、對日志url匯總規則:1、不對以css、txt等下面列表中后綴的url統計;2、通過空格分割,統計日志中的訪問路徑,存在嗎?的路徑只選取?前面的路徑;3、由于可能存在不標準的日志格式,此處的切割規則也會不同,可以根據實際情況再做修改;
def countfiles():
info,count=rizhi_find.open_file()
for i in info:
if len(i.strip().split(' '))>6 and i.strip().split(' ')[6].endswith(('css', 'CSS', 'dae', 'DAE', 'eot', 'EOT', 'gif', 'GIF', 'ico', 'ICO', 'jpeg','JPEG', 'jpg', 'JPG', 'js', 'JS', 'map', 'MAP', 'mp3', 'MP3', 'pdf', 'PDF', 'png','PNG', 'svg', 'SVG', 'swf', 'SWF', 'ttf', 'TTF', 'txt', 'TXT', 'woff','WOFF')) == False:
path=i.strip().split('"')[1].rstrip(' HTTP/1.1')
# print path.rstrip(' HTTP/1.1')
time=i.strip().split(' ')[3]
# print time
url=path.split('?')[0]
url_list.append(url)
result = Counter(url_list)
result1 = dict(result)
# print result1
res = sorted(result1.items(), key=lambda d: d[1], reverse=True)
# 3、這里是保存了url訪問量前20的數據,也可以在做修改。
for i in range(0,20):
fangwen_url= res[i][0]
bili="%.2f%%" % (round(float(res[i][1])/float(count),2) * 100)
fangwen_cishu=res[i][1]
aa= i, fangwen_url,fangwen_cishu,bili
bb.append(aa)
return bb
# 4、將輸出結果保存到url_tongji.xls的表格中
def baocun_url_biaoge():
path=os.getcwd() + "/result/"
if not os.path.exists(path):
os.makedirs(path)
else:
pass
workbook = xlwt.Workbook(encoding='utf-8')
sheet = workbook.add_sheet('url_tongji',cell_overwrite_ok=True)
sheet1 = workbook.add_sheet('ip_tongji',cell_overwrite_ok=True)
head = ['序號', '訪問次數', '訪問占比' ,'url'] # sheet表頭
head1 = ['序號', 'ip', '訪問次數' ,'ip歸屬地'] # sheet表頭
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style = xlwt.XFStyle() # Create Style
font = xlwt.Font() # 為樣式創建字體
font.name = 'SimSun'
font.bold = False # 黑體
style.font = font
style.alignment = alignment # Add Alignment to Style
for h in range(len(head)):
sheet.write(0, h, head[h],style)
result=countfiles()
sheet.col(0).width = 256 * 5
sheet.col(1).width = 256 * 15
sheet.col(2).width = 256 * 15
sheet.col(3).width = 256 * 50
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
i=1
for a in result:
sheet.write(i,0,a[0],style)
sheet.write(i,1, a[2],style)
sheet.write(i, 2, a[3],style)
sheet.write(i, 3, a[1],style)
i += 1
# 5、生成ip查詢情況統計表,此處只是統計了出現20次以上的ip地址;
for h1 in range(len(head1)):
sheet1.write(0, h1, head1[h1],style)
result1=rizhi_find.ip_guishudi()
sheet1.col(0).width = 256 * 5
sheet1.col(1).width = 256 * 20
sheet1.col(2).width = 256 * 15
sheet1.col(3).width = 256 * 50
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
h=1
for b in range(len(result1)):
quzhi= result1[b]
# print quzhi
sheet1.write(h,0,quzhi[0],style)
sheet1.write(h,1, quzhi[1],style)
sheet1.write(h, 2, quzhi[3],style)
sheet1.write(h, 3, quzhi[2],style)
h += 1
workbook.save(path+'tongji.xls')
print "請在"+path+"文件夾下查看相關結果"
if __name__=="__main__":
baocun_url_biaoge()
# countfiles()
使用手冊
一、概述
在系統被入侵后,要想了解下系統被入侵的過程,最好的途徑大概就是通過查看日志,對日志進行分析,來還原整個過程的來龍去脈。每次對幾百兆的日志進行查看時確實頭疼,尤其是對關鍵字進行搜索時還會出現編輯器卡頓的情況。所以就想著能不能利用腳本去完成一些常規的排查過程,來輔助完成日志分析工作,先簡單說下日志分析的思路,此處只是對于web日志進行分析。
二、功能簡述
1、根據關鍵字進行搜索
1) 目的:嘗試通過在日志中搜索后門名稱、時間等關鍵字,更快找到有用信息。
2) 使用方法:運行rizhi_find.py,該模塊最多支持兩個關鍵字搜索,關鍵字之間以逗號隔開,
當最后一個關鍵字為1時,表示對關鍵字1和關鍵字2同時進行搜索;
當最后一個關鍵字為2時,表示搜索滿足關鍵字1或關鍵字2的日志;
當最后一個關鍵字為空時,表示只是對關鍵字1進行搜索;
3) 結果保存:搜索出的結果均會保存在當前目錄下的find_result.txt文檔中。
如搜索test.php,輸入格式test.php,, 輸出如下:
搜索10月6號訪問test.php的日志,輸入格式test.php, 06/Oct/,1 輸出如下:
搜索10月6號或訪問test.php的日志,輸入格式test.php, 06/Oct/,2 輸出如下:
4) ip地址查詢:
對搜索到結果進行ip地址提取,查看攻擊者的ip還做過哪些操作,并將搜索結果保存在log.txt中
2、Ip、url分析
1) 目的:提取日志中所有的ip地址,并對ip歸屬地進行查詢,并對出現次數做統計;根據日志分析url訪問情況,記錄訪問路徑、訪問次數,并將結果保存到tongji.xsl表格中。
2) 使用方法:將需要查詢的日志放到當前路徑/log/目錄下,運行python rizhifenxi.py。
3) 結果保存:會在result目錄下生成tongji.xls。
url統計表
Ip地址統計表
三、有待改進
1、腳本思路多數來自平常的項目積累,所以想法過于單一,在今后遇到不同的情況會再繼續完善;
2、很多時候即使是篩選出來后還是更多的靠人為去分析,腳本只是輔助工具,所以存在不夠通用的問題;
3、ip地址在查詢中由于查詢接口原因,會存在查詢失敗的情況;
4、當日志格式為自定義情況下,需要根據定義格式在自行修改腳本中分割日志的格式;
總結
以上是生活随笔為你收集整理的用于日志分析分析日志文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 发力5G平板市场,品网科技首发展锐5G平
- 下一篇: 游戏 (博弈论)