python程序提取唯一的IP地址并保存到另一个文件中

时间:2016-12-16 12:11:17

标签: python

我尝试从snort日志文件中提取唯一的IP地址,并将它们存储在单独的文件中。如果存在则忽略它。但输出也显示重复的IP地址。我该如何防止这种情况?

这是我的代码:

#!/usr/bin/python
import re
lst = []
lst2 = []
lstb = []
logfile = open('/var/log/snort/alllogs', 'r')
blist = open('blacklist', 'ab+')
for lines in logfile.readlines():
 lines = lines.rstrip()
 badip = re.findall(r'[0-9]+(?:\.[0-9]+){3}',lines)
 if badip is not None and badip not in lst:
   lst.append(badip)
for ip in lst:
  addr = ",".join(ip)
 if ',' in addr:
   s = addr.split(',')
    for ip in s:
        addr = "".join(ip)
        if addr is not '':
            lst2.append(addr)
        else:
            if addr is not '':
                lst2.append(addr)
for i in blist:
  lst2.append(i.strip())
for i in lst2:
  if i not in lstb:
    blist.write(i+'\n')'

结果是:

192.168.12.10
192.168.1.120
192.168.1.120
192.168.12.10

2 个答案:

答案 0 :(得分:1)

您正在检查:

if i not in lstb 

但是你的代码中从不使用lstb。

答案 1 :(得分:0)

您可以使用以下单行删除列表中的重复项:

lst2 = list(set(lst2))

我不知道你在哪里填写lstb,这可能是你的解决方案无法解决的原因。

如果你想修复你的解决方案,可以考虑这样的事情:

for i in lst2:
      if i not in lstb:
        blist.write(i+'\n')
        lstb.append(i)