【发布时间】:2015-03-03 23:15:36
【问题描述】:
所以,我最近开始学习 python,在工作中我们想要一些方法来简化在我们的日志文件中查找特定关键字的过程,以便更容易地告诉哪些 IP 将添加到我们的阻止列表中。
我决定编写一个 python 脚本,它会接收一个日志文件,接收一个包含关键术语列表的文件,然后在日志文件中查找这些关键术语,然后编写与会话匹配的行找到该关键术语的 ID;到一个新文件。
import sys
import time
import linecache
from datetime import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.now().strftime(fmt).format(fname=fname)
importFile = open('rawLog.txt', 'r') #pulling in log file
importFile2 = open('keyWords.txt', 'r') #pulling in keywords
exportFile = open(timeStamped('ParsedLog.txt'), 'w') #writing the parsed log
FILE = importFile.readlines()
keyFILE = importFile2.readlines()
logLine = 1 #for debugging purposes when testing
parseString = ''
holderString = ''
sessionID = []
keyWords= []
j = 0
for line in keyFILE: #go through each line in the keyFile
keyWords = line.split(',') #add each word to the array
print(keyWords)#for debugging purposes when testing, this DOES give all the correct results
for line in FILE:
if keyWords[j] in line:
parseString = line[29:35] #pulling in session ID
sessionID.append(parseString) #saving session IDs to a list
elif importFile == '' and j < len(keyWords): #if importFile is at end of file and we are not at the end of the array
importFile.seek(0) #goes back to the start of the file
j+=1 #advance the keyWords array
logLine +=1 #for debugging purposes when testing
importFile2.close()
print(sessionID) #for debugging purposes when testing
importFile.seek(0) #goes back to the start of the file
i = 0
for line in FILE:
if sessionID[i] in line[29:35]: #checking if the sessionID matches (doing it this way since I ran into issues where some sessionIDs matched parts of the log file that were not sessionIDs
holderString = line #pulling the line of log file
exportFile.write(holderString)#writing the log file line to a new text file
print(holderString) #for debugging purposes when testing
if i < len(sessionID):
i+=1
importFile.close()
exportFile.close()
它没有遍历我的关键字列表,我可能犯了一些愚蠢的新手错误,但我没有足够的经验来意识到我搞砸了什么。当我检查输出时,它只在 rawLog.txt 文件的 keyWords 列表中搜索第一项。
第三个循环确实返回基于第二个列表提取并尝试迭代的 sessionID 出现的结果(这给出了一个超出范围的异常,因为 i 永远不会小于 sessionID 列表的长度,因为sessionID 只有 1 个值)。
程序确实成功地写入并命名了新的日志文件,日期时间后跟 ParsedLog.txt。
【问题讨论】:
-
这是
j+=1 #advance the keyWords array否则。如果这是真的if keyWords[j] in line:,它将不会执行。也许这就是原因? -
这里的预期行为是什么?对于每一行,查找至少一次出现的关键字,并保存 sessionID?或者对于每一行和每个关键字,如果在该行中找到关键字,则保存 sessionID(即您可以多次保存同一行?)
-
您的第一个断言,“对于每一行,查找至少一次出现的关键字,并保存 sessionID?”是正确的。基本上,寻找奇怪的登录行为,然后保存发生奇怪登录行为的 sessionID。
标签: python python-3.x