【问题标题】:How to approach IIS log parsing in a Pythonic way?如何以 Pythonic 方式处理 IIS 日志解析?
【发布时间】:2011-09-24 03:09:38
【问题描述】:

好的,所以我有一些我想用 Python 解析的 IIS 日志(我对 atm 相当陌生)。 IIS 日志示例如下所示:

#Software: Microsoft Internet Information Server 6.0 
#Version: 1.0 
#Date: 1998-11-19 22:48:39 
#Fields: date time c-ip cs-username s-ip cs-method cs-uri-stem cs-uri-query sc-status sc-bytes cs-bytes time-taken cs-version cs(User-Agent) cs(Cookie) cs(Referrer) 

1998-11-19 22:48:39 206.175.82.5 - 208.201.133.173 GET /global/images/navlineboards.gif - 200 540 324 157 HTTP/1.0 Mozilla/4.0+(compatible;+MSIE+4.01;+Windows+95) USERID=CustomerA;+IMPID=01234 http://www.loganalyzer.net
1998-11-20 22:55:39 206.175.82.8 - 208.201.133.173 GET /global/something.pdf - 200 540 324 157 HTTP/1.0 Mozilla/4.0+(compatible;+MSIE+4.01;+Windows+95) USERID=CustomerA;+IMPID=01234 http://www.loganalyzer.net

这里只有 2 行日志数据,每个日志有数千行。所以,这只是一个简短的示例。

我想从这个日志中提取数据,例如 - 建立最多连接的客户端 IP 地址的计数、下载最多的文件的计数、访问最多的 URI 的数量等等......基本上我想要得到一些统计数据...例如,结果我希望看到这样的结果:

file download_count
example1.pdf 9
example2.pdf 6
example3.doc 2

IP file hits
192.168.1.5 /sample/example1.gif 8
192.168.1.9 /files/example2.gif 8

我不确定如何以 Python 的方式处理这个问题。起初我以为我会拆分日志的每一行并从中列出一个列表,然后将每一行附加到一个更大的列表中(我将其视为二维数组)。然后我进入了从那个大列表中提取统计数据的阶段,现在我认为从所有这些数据中制作一个字典并通过 dict 键和 dict 值计算内容可能会更好?这比使用列表更好吗?如果我应该更好地使用列表,我应该如何处理它?我用谷歌搜索什么,我在寻找什么?

所以我正在寻找有关通常应该如何完成的想法。谢谢。

【问题讨论】:

  • google "python IIS parser" 并查看前 2 个匹配项(第三个是您的问题)

标签: parsing iis python


【解决方案1】:

假设skip_header(file) 仅返回文件中的日志行,并且parse(line) 从行中提取(ip, path)

from collections import defaultdict
first = defaultdict(int)
second = defaultdict(lambda: defaultdict(int))
for line in skip_header(file):
    ip, path = parse(line)
    first[path] += 1
    second[ip][path] += 1

第一个

print "path count"
for path, count in first.iteritems():
    print "%s %d" % (path, count)

第二次:

print "ip path count"
for ip,d in second.iteritems():
     for path, count in d.iteritems():
         print "%s %s %d" % (ip, path, count)

【讨论】:

  • 感谢丹。顺便说一句,我使用了 python3,所以如果有人尝试这个,你需要使用 items() 而不是 iteritems(),当然还有 print()。
猜你喜欢
  • 2018-09-30
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2012-05-15
相关资源
最近更新 更多