Python脚本可以查找超过30种攻击的IP地址

时间:2016-02-20 16:10:28

标签: python regex python-2.7

我正在尝试创建一个Python脚本,允许我搜索auth.log文件并搜索超过30次失败尝试的IP地址,然后创建一个黑名单文件,然后保存这些IP地址。这是我到目前为止所做的,但正则表达似乎不起作用:

#!/usr/bin/python
import re # allows me to use regular expressions 

#attempts = 0 #setting the variable 'attempts' to 0
myAuthlog=open('auth.log', 'r') #open the auth.log for reading

#open the Security_Test.txt for writing later
myTxtFile = open('blacklistips.txt','w')

#write to the file what we are analysing
myTxtFile.write('The security options for httpd.conf\n')

for line in myAuthlog: #go through each line of the file and return it to the variable line
    if re.match("([0-9]{1,3}\.){3}[0-9]{1,3}$'", line): #if the regular expressions matches 'bin' or 'Bin' in line

日志文件中的一个示例是:

Feb  5 08:34:51 j4-be02 sshd[2281]: Failed password for root from 5.199.133.223 port 42582 ssh2
Feb  5 08:34:56 j4-be02 sshd[2283]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=5.199.133.223  user=root
Feb  5 08:34:58 j4-be02 sshd[2283]: Failed password for root from 5.199.133.223 port 50099 ssh2
Feb  5 08:35:04 j4-be02 sshd[2285]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=5.199.133.223  user=root

我需要搜索此文件并查找所有IP地址和authentication failure,如果有超过30个失败,则将这些IP地址写入文本文件。

2 个答案:

答案 0 :(得分:0)

您必须将匹配的IP存储到集合中,然后在完成迭代所有行处理集合并查看每个唯一IP的计数后,如果它超过30个写入值到文件中。使用的集合可能是dictonary。

答案 1 :(得分:0)

以下类型的方法应该可以正常工作。它利用Python的Counter来累计所有匹配的IP地址。然后它将任何已被看到超过30次的任何内容写入黑名单文件:

from collections import Counter
import re

with open('auth.log') as f_authlog:
    authlog = f_authlog.read()
    ip_addresses = Counter(re.findall(r'authentication failure.*?rhost=([0-9.]*)\s', authlog))

with open('blacklist.txt', 'w') as f_blocked:
    for ip_address, count in ip_addresses.iteritems():
        if count > 30:
            f_blocked.write('{}\n'.format(ip_address))