【问题标题】:Python Script to find IP address with more than 30 attacks用于查找具有超过 30 次攻击的 IP 地址的 Python 脚本
【发布时间】:2016-02-20 16:10:27
【问题描述】:

我正在尝试创建一个 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 地址将写入文本文件。

【问题讨论】:

  • 您的问题的标题过于宽泛,无法回答,而且您的问题不是问题——它是一个脚本和一个声明,它说它不起作用。告诉我们您要解决的问题、遇到的问题、您尝试解决的问题以及一些示例输入和输出。
  • 你能展示auth.log的结构并告诉我们正则表达式应该做什么吗?
  • 上面更新了,我需要搜索这个文件并找到所有的 IP 地址和“身份验证失败”,如果有超过 30 个失败,这些 IP 地址会被写入文本文件

标签: python regex python-2.7


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    以下方法应该可以正常工作。它利用 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))
    

    【讨论】:

      猜你喜欢
      • 2011-10-22
      • 2010-09-15
      • 1970-01-01
      • 2011-04-04
      • 2020-11-01
      相关资源
      最近更新 更多