首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Python将来自日志文件的输出相加

如何使用Python将来自日志文件的输出相加
EN

Stack Overflow用户
提问于 2017-12-05 13:41:02
回答 1查看 48关注 0票数 0

我需要使用Python脚本从日志文件中输出每小时一次的攻击量。我成功地完成了这一切,但无法想出如何将攻击的数量加到最后的总数中。除了简单的计算之外,我缺乏所需的知识来理解总函数是如何工作的。提前感谢您的帮助。

代码语言:javascript
复制
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)

我希望结果是:

代码语言:javascript
复制
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

我真正得到的是:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-05 13:59:11

变量名称大小写确实很重要。只要换行就行:

代码语言:javascript
复制
Total = total +1

代码语言:javascript
复制
total = total + len(list(group))

因为在循环中,您的totals计数器是不正确的:相反,它只计算迭代计数。而在每个循环步骤中创建的新变量Total的值设置正在松动。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47655045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档