【问题标题】:Sortin apache log with Python使用 Python 对 apache 日志进行排序
【发布时间】:2016-08-09 10:41:48
【问题描述】:

例如我有这个简单的 apache 日志:

192.168.1.1 GET /index.php
192.168.1.1 GET /pilt.png
192.168.1.1 GET /index.php
192.168.1.5 GET /index.php
192.168.1.5 GET /pilt.png
192.168.1.7 GET /index.php
192.168.1.7 GET /index.php
192.168.1.7 GET /index.php
192.168.1.7 GET /kaust/index.php
192.168.1.7 GET /index.php

我将如何编写 Python 代码来整理出所有相似的 IP 地址都在一起并计算有多少 IP 地址

w = open("C:\\Users\\xxx\\Desktop\\test.txt","r")

for i in w:
  log=i.split(' ')
  print log[0]
w.close()

尝试了这么多,但无法进一步编写代码。

谢谢!

【问题讨论】:

  • 您需要对 IP 地址进行排序和所有唯一 IP 地址的功能。对吧??
  • 你能告诉我们你到底想要什么输出吗?
  • 这是一本字典,我猜是 192.168.1.1 : 3 192.168.1.5 : 2 等等

标签: python apache python-2.7


【解决方案1】:

这将是如何完成的:

x = open('PATH_TO_FILE').read()

from itertools import groupby
from operator import itemgetter
x = x.split('\n')
for i in range(len(x)):
    x[i] = x[i].split(' ')

j = 0

for elt, items in groupby(x, itemgetter(0)):
    j += 1
    k = 0
    print elt, items
    for i in items:
        k += 1
        print i
    print 'Total count for IP ',i[0],' is :',k

print 'Total unique IP address are : ',j

【讨论】:

  • 没有只使用python 2.7,但是你是否从中删除了 read() ??
  • 是的,我的错....但我想在每个重复 IP 之后计数。所以它就像一本字典
  • 已更改,请验证。
  • 所以我必须导入其他库,没有基本的方法吗?
  • 如果你想自己做所有事情,那会很长。
【解决方案2】:

您可以将defaultdict(int) 用于您的目的:

from collections import defaultdict
my_dict = defaultdict(int)
w = open("C:\\Users\\xxx\\Desktop\\test.txt", "r")
for line in w:
    ip = line.split(' ')[0]
    my_dict[ip]+=1

my_dict  # defaultdict(<class 'int'>, {'192.168.1.7': 5, '192.168.1.1': 3, '192.168.1.5': 2})

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 2016-09-18
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多