我有一个名为" log"的snort日志文件。并希望从中提取IP地址并将其存储到另一个名为" blacklist"的文件中。它可以提取唯一的IP地址,但如果我再次运行该程序,它也会添加以前的IP。我希望程序首先检查IP是否已经在黑名单文件中?如果是这样,请忽略它,否则将日志文件中的唯一IP添加到黑名单。代码:
#!/usr/bin/python
import re
mylist1 = []
mylist2 = []
mylist3 = []
mylist4 = []
logfile = open('/var/log/snort/logs', 'r')
blklist = open('blacklist', 'ab+')
for line in open ('blacklist', 'r').readlines():
mylist4.append(line)
for l in logfile.readlines():
l = l.rstrip()
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}',l)
if ip is not None and ip not in mylist1:
mylist1.append(ip)
for ip in mylist1:
addr = ",".join(ip)
if ',' in addr:
a = addr.split(',')
for ip in a:
addr = "".join(ip)
if addr is not '':
mylist2.append(addr)
else:
mylist3.append(addr)
for x in blklist:
mylist2.append(x.strip())
for x in mylist2:
if x not in mylist3 and x not in mylist4:
blklist.write(x+'\n')
mylist3.append(x)
日志文件是:
12/16-10:34:27.070967 [**] [1:10000001:1] snort alert [1:0000001] [**][classification ID: 0] [Priority ID: 0] {ICMP} 192.168.40.19 -> 192.168.50.29
12/16-10:34:27.070967 [**] [1:10000001:1] snort alert [1:0000001] [**][classification ID: 0] [Priority ID: 0] {ICMP} 192.168.50.29 -> 192.168.30.20
首次运行程序后输出黑名单文件:
192.168.30.20
192.168.50.29
192.168.40.19
第二次程序运行后输出黑名单文件:
192.168.30.20
192.168.50.29
192.168.40.19
192.168.30.20
192.168.50.29
192.168.40.19
有什么帮助吗?
答案 0 :(得分:0)
您可以使用仅存储唯一元素的Python容器类型set
。以下程序适合您:
create a 'current' blacklist set
read the blacklist file IP's into the current set
create a 'delta' blacklist set
for each IP address in the log file
if not already in current blacklist
add the IP into the delta set
append (by writing) the delta set into the black list file
答案 1 :(得分:0)
您可以从黑名单文件中读取所有内容并登录列表。加入这些列表,然后将一个集合输出回黑名单文件(集合是唯一值),因为读取清空文件,您将拥有所有新旧IP的唯一列表。如果订单很重要(怀疑它确实如此)那么一套将导致问题。让我知道,我可以改进下面的内容。
Dictionary