【问题标题】:how to get unique ip address from list of ip address present in log file using python?如何使用python从日志文件中存在的IP地址列表中获取唯一的IP地址?
【发布时间】:2012-03-26 13:48:12
【问题描述】:

我有一个文本文件格式的日志文件。日志文件看起来像下面的格式

220.227.40.118 - - [06/Mar/2012:00:00:00 -0800] "GET /mysidebars/newtab.html 
HTTP/1.1" 404 0 - -
220.227.40.118 - - [06/Mar/2012:00:00:00 -0800] "GET /hrefadd.xml HTTP/1.1" 
204 214 - -
59.95.13.217 - - [06/Mar/2012:00:00:00 -0800] "GET /dbupdates2.xml HTTP/1.1" 
404 0 - -

111.92.9.222 - - [06/Mar/2012:00:00:00 -0800] "GET /mysidebars/newtab.html 
HTTP/1.1" 404 0 - -
120.56.236.46 - - [06/Mar/2012:00:00:00 -0800] "GET /hrefadd.xml HTTP/1.1" 
204 214 - -
49.138.106.21 - - [06/Mar/2012:00:00:00 -0800] "GET /add.txt HTTP/1.1" 204 
214 - -

117.195.185.130 - - [06/Mar/2012:00:00:00 -0800] "GET 
/mysidebars/newtab.html HTTP/1.1" 404 0 - -
122.160.166.220 - - [06/Mar/2012:00:00:00 -0800] "GET 
/mysidebars/newtab.html HTTP/1.1" 404 0 - -
117.214.20.28 - - [06/Mar/2012:00:00:00 -0800] "GET /welcome.html HTTP/1.1" 
204 212 - -
117.18.231.5 - - [06/Mar/2012:00:00:00 -0800] "GET /mysidebars/newtab.html 
HTTP/1.1" 404 0 - -

我想使用 python 查找日志文件中存在的每个唯一 IP 地址。

【问题讨论】:

  • 既然 perl -lane 'print $F[0] unless $seen{$F[0]}++' logfile1 logfile2 logfile3 已经为您完成了这项工作,为什么还要使用 python?
  • @tchrist 应该扩展为答案
  • @tchrist 但我的要求是在 python 上。
  • $ sort -uk1,1 已经完成这项工作了,为什么还要使用 perl?

标签: python ip-address


【解决方案1】:

怎么样:

def get_ips(logfile):
    with open(logfile, 'r') as f:
        for line in f.readlines():
            yield line.split()[0]


def main():
    for ip in set(get_ips('log.txt')):
        print ip


if __name__ == '__main__':
    main()

【讨论】:

  • @Raju.allen,你用的是哪个版本的 Python?
  • 你可以使用for line in f:。这样做更好,因为它避免了一次将整个文件读入内存
  • @Raju.allen,该代码在 Python2.6 中应该可以正常工作。您是复制/粘贴还是重新输入?
【解决方案2】:

方法如下:

def unique_ips():
    f = open('log_file.txt','r')
    ips = set()
    for line in f:
        ip = line.split()[0]
        ips.add(ip)
    return ips

if __name__=='__main__':
    print unique_ips()

这应该适用于python 2.6

【讨论】:

  • ip not in ips 如果有很多不同的 ip 地址,会变得很慢。 ips 应该是一个集合
  • 现在你可以写ips = set(line.split()[0] for line in f)。如果有任何空行,split()[0] 将中断
  • 嗯,我知道这也可以,但不是在这里保存行。我想更清楚。
  • ips = set(line.split()[0] for line in f if not line.isspace()) 会更好
  • 感谢@gnibbler,它工作正常。我在日志文件中有 243607 个 ips。输出连续显示,因此我无法检查输出。我希望每个 ip 在单独的行中打印。因为我是 python 新手,所以我无法弄清楚。有什么办法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多