我需要使用Python脚本从日志文件中输出每小时一次的攻击量。我成功地完成了这一切,但无法想出如何将攻击的数量加到最后的总数中。除了简单的计算之外,我缺乏所需的知识来理解总函数是如何工作的。提前感谢您的帮助。
import re
from itertools import groupby
total = 0
with open(log_file) as Authlog:
Authlog = (line for line in Authlog if "Failed password for" in line)
for key, group in groupby(Authlog, key = lambda x: x[:9] + re.search('from(.+?) port', x).group(1)):
hour, month, day = key[0:3], key[4:6], key[7:9]
print ("Within the hour of %s:00 on %s-%s There was %d attacks"%(day, month, hour, len(list(group))))
Total = total +1
print("Total amount of attacks: %s" % total)我希望结果是:
Within the hour of 08:00 on 3-Feb There was 172 attacks
Within the hour of 13:00 on 3-Feb There was 4 attacks
Within the hour of 21:00 on 3-Feb There was 1 attacks
Within the hour of 08:00 on 4-Feb There was 15 attacks
Within the hour of 10:00 on 4-Feb There was 58 attacks
Within the hour of 10:00 on 4-Feb There was 2 attacks
Within the hour of 16:00 on 4-Feb There was 4 attacks
Within the hour of 07:00 on 5-Feb There was 24 attacks
Within the hour of 08:00 on 5-Feb There was 86 attacks
Total amount of attacks: 366我真正得到的是:
Within the hour of 08:00 on 3-Feb There was 172 attacks
Within the hour of 13:00 on 3-Feb There was 4 attacks
Within the hour of 21:00 on 3-Feb There was 1 attacks
Within the hour of 08:00 on 4-Feb There was 15 attacks
Within the hour of 10:00 on 4-Feb There was 58 attacks
Within the hour of 10:00 on 4-Feb There was 2 attacks
Within the hour of 16:00 on 4-Feb There was 4 attacks
Within the hour of 07:00 on 5-Feb There was 24 attacks
Within the hour of 08:00 on 5-Feb There was 86 attacks
Total amount of attacks: 9发布于 2017-12-05 13:59:11
变量名称大小写确实很重要。只要换行就行:
Total = total +1至
total = total + len(list(group))因为在循环中,您的totals计数器是不正确的:相反,它只计算迭代计数。而在每个循环步骤中创建的新变量Total的值设置正在松动。
https://stackoverflow.com/questions/47655045
复制相似问题