我的背景:我是一名网络工程师,并开始学习python以自动执行任务。我没有太多的编码经验。我需要帮助来理解和解决编码问题,我花了很多时间来使用python解决此编码问题,但是没有运气。我已经附上我到目前为止在这个问题上所做的事情。
# read file
with open("C:\py\logfile.txt") as file:
next(file)
lines = file.read().splitlines()
file.close()
matchEst = []
matchFail = []
matchSyn = []
counterEst = 0
counterFail = 0
counterSyn = 0
for line in lines:
line = line.strip()
if line.find('Established') != -1:
matchEst.append(line)
elif line.find('Failed') != -1:
matchFail.append(line)
elif line.find('Syn') != -1:
matchSyn.append(line)
print(matchEst)
print(matchFail)
print(matchSyn)
输出:
['9/1/2013 1.1.1.1 0:10 Established', '9/1/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.2 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established', '9/2/2013 1.1.1.1 0:10 Established']
['9/1/2013 1.1.1.2 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed', '9/2/2013 1.1.1.1 0:10 Failed']
['9/1/2013 1.1.1.1 0:10 Syn', '9/2/2013 1.1.1.1 0:10 Syn', '9/2/2013 1.1.1.1 0:10 Syn']
代码说明:解析文件“ logfile.txt”并打印每天每个IP的状态计数。
cat logfile.txt
-----------------
Date IP Time State
9/1/2013 1.1.1.1 0:10 Established
9/1/2013 1.1.1.2 0:10 Failed
9/1/2013 1.1.1.1 0:10 Syn
9/1/2013 1.1.1.1 0:10 Established
9/2/2013 1.1.1.1 0:10 Established
9/2/2013 1.1.1.1 0:10 Failed
9/2/2013 1.1.1.1 0:10 Failed
9/2/2013 1.1.1.1 0:10 Established
9/2/2013 1.1.1.2 0:10 Established
9/2/2013 1.1.1.1 0:10 Established
9/2/2013 1.1.1.1 0:10 Failed
9/2/2013 1.1.1.1 0:10 Established
9/2/2013 1.1.1.1 0:10 Syn
9/2/2013 1.1.1.1 0:10 Syn
输出应如下所示:
9/1/2013 1.1.1.1 Established 2
9/1/2013 1.1.1.2 Failed 1
9/1/2013 1.1.1.1 Syn 1
9/2/2013 1.1.1.1 Established 4
9/2/2013 1.1.1.1 Failed 3
9/2/2013 1.1.1.1 Syn 2
9/2/2013 1.1.1.2 Established 1
谢谢!
答案 0 :(得分:0)
由于您将所有结果存储在列表中,因此只需在末尾打印每个列表的长度即可。
print("Established count = " + str(len(matchEst)))
print("Failed count = " + str(len(matchFail)))
print("Syn count = " + str(len(matchSyn)))
如果您希望查看每个不同IP的数量 / ,那么还有更多工作要做。
答案 1 :(得分:0)
在您的代码中,您正在with
语句中打开文件,这意味着它将自动关闭。无需显式调用close()
。
对于任何字符串操作/搜索,最好了解正则表达式(在Python re
模块中)。要计算变量,您可以使用Counter
中的itertools
。这是一个示例:
from collections import Counter
import re
with open('logfile.txt', 'r') as f:
data_in = f.read()
columns = re.findall(r'([\d\/]+)\s+([\d\.]+)\s+([\d:]+)\s+([a-zA-Z]+)', data_in)
c = Counter(columns)
for (column_1, column_2, column_3, column_4), count in c.items():
print(column_1, column_2, column_3, column_4, count)
打印:
9/1/2013 1.1.1.1 0:10 Established 2
9/1/2013 1.1.1.2 0:10 Failed 1
9/1/2013 1.1.1.1 0:10 Syn 1
9/2/2013 1.1.1.1 0:10 Established 4
9/2/2013 1.1.1.1 0:10 Failed 3
9/2/2013 1.1.1.2 0:10 Established 1
9/2/2013 1.1.1.1 0:10 Syn 2