计算每个IP地址每小时的攻击次数

时间:2020-03-22 16:42:33

标签: python

我有两个文件:{ _id: ObjectId("7a917971947913749") bar: 2700 other: "stuff1" }, { _id: ObjectId("7a917971947913750") bar: 2800 other: "stuff2" } 文件和access,它们显示有关登录尝试的信息。

我正在尝试搜索整个文档并计算失败的密码尝试次数,然后显示每个IP地址每小时失败的尝试次数。

这是我正在努力解决的每个IP地址部分。我有显示每小时失败尝试次数的代码,但无法弄清楚如何按照每小时IP地址显示它。

auth.log

此代码当前显示结果如下:

from itertools import groupby

with open('auth.log') as myAuthlog:
     myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
     for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
        month, day, hour = key[0:3], key[4:6], key[7:9]
        print ("%s:00 %s-%s: %d"%(hour, day, month, len(list(group))))

任何建议或帮助将不胜感激。

08:00  3-Feb: 172
13:00  3-Feb: 4
21:00  3-Feb: 1
08:00  4-Feb: 15
10:00  4-Feb: 60
16:00  4-Feb: 4
07:00  5-Feb: 24
08:00  5-Feb: 86

谢谢

1 个答案:

答案 0 :(得分:1)

这里仅是描述攻击的相关内容,我将前三名更改为另一个IP地址,以便我们可以看到两个不同的攻击者。

Feb  3 08:35:23 j4-be02 sshd[32741]: Failed password for root from 211.167.103.148 port 34583 ssh2
Feb  3 08:35:29 j4-be02 sshd[32744]: Failed password for root from 211.167.103.148 port 36610 ssh2
Feb  3 08:35:35 j4-be02 sshd[32747]: Failed password for root from 211.167.103.148 port 38355 ssh2
Feb  3 08:35:40 j4-be02 sshd[32749]: Failed password for root from 211.167.103.172 port 40252 ssh2
Feb  3 08:35:46 j4-be02 sshd[32751]: Failed password for root from 211.167.103.172 port 42099 ssh2
Feb  3 08:35:52 j4-be02 sshd[32753]: Failed password for root from 211.167.103.172 port 44102 ssh2
Feb  3 08:35:58 j4-be02 sshd[32755]: Failed password for root from 211.167.103.172 port 45932 ssh2

现在此代码将实现您想要的:

from itertools import groupby
import re, json

with open('auth.log') as myAuthlog:
    myAuthlog = (line for line in myAuthlog if "Failed password for" in line)
    attacks = {}
    for key, group in groupby(myAuthlog, key = lambda x: x[:9]):
        group_list = list(group)
        month, day, hour = key[0:3], key[4:6], key[7:9]
        datetime_attacks = f"{hour}:00 {day}-{month}: {len(group_list)}"
        attacks[datetime_attacks] = {}
        for e in group_list:
            ip = re.search(r'Failed password for root from ([\d\.]+?) ', e)
            if ip:
                ip = ip.group(1)
                if ip not in attacks[datetime_attacks]:
                    attacks[datetime_attacks][ip] = 0
                attacks[datetime_attacks][ip] += 1

print(json.dumps(attacks, indent=2, sort_keys=True))

>> {
>>   "08:00  3-Feb: 7": {
>>     "211.167.103.148": 3,
>>     "211.167.103.172": 4
>>   }
>> }
相关问题