【发布时间】: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