如何用python正则表达式和包含IP和数值的键值字典解析日志文件

2024-04-25 19:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析这个(https://bpaste.net/raw/477b79a86b42)日志文件,该文件旁边包含数字和IP的特定格式的输出。我想获取IP地址并对连接总数进行求和,例如使用以下语法:

[0;32m192.168.1.34 | SUCCESS | rc=0 >>
2
192.168.1.97
5
192.168.1.152
3
192.168.2.108
11
192.168.2.144
[0m
[0;32m192.168.1.18 | SUCCESS | rc=0 >>
2
192.168.1.97
3
192.168.1.152
14
192.168.2.108
7
192.168.2.144
[0m
[0;32m192.168.2.137 | SUCCESS | rc=0 >>
5
192.168.1.97
10
192.168.1.152
53
192.168.2.108
6
192.168.2.144
[0m
[0;32m192.168.1.96 | SUCCESS | rc=0 >>

脚本的输入应该被读取为file,存储数字和IP,然后输出应该是IP&sum,For。e、 g.192.168.97:84,192.168.1.152:66

在下面的python脚本中,我想利用集合。计数器,regex和键值字典进行迭代,我的初始代码版本如下:

^{pr2}$

我可以在两个序列上使用循环,获取ip并存储在第一个序列中,然后在另一个序列中求和,如果是,那么我应该如何编写逻辑,我对python伪代码的最初想法是:

conn_n = ['2', '5', '3']
ip_seq = ['192.168.1.97', '192.168.1.152', '192.168.1.108']
dict = {"conn_n":"ip_seq"}

for key,val in d.items():
      if line.startswith('['):
      print re.findall(r'/^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/', line)
      ....
      ....
      print("{} = {}".format(key, val))

我真的很感激有什么方法来解决这个问题,我应该使用列表和循环遍历它还是字典?在

提前感谢您的帮助!在


Tags: 文件key代码ip脚本字典line序列
1条回答
网友
1楼 · 发布于 2024-04-25 19:30:54

我认为你根本不需要使用正则表达式。只要注意你台词的性质。我选择创建生成器,以便更容易理解发生的事情:

#!/usr/bin/env python2.7

import collections
import ssl    # See note in logfile_lines, below
import urllib

LOGFILE = r'https://bpaste.net/raw/477b79a86b42'

def logfile_lines(url):

    # NOTE: This business of `_create_unverified_context` is because I 
    # don't have py2.7 set up correctly w/r/t ssl. I normally use py3.
    # If you're stuck using 2.7, go ahead and get your certificate verification 
    # working properly!

    logfile = urllib.urlopen(url, context=ssl._create_unverified_context())

    for line in logfile:
        if ' |' in line:
            continue

        if not line[0].isdigit():
            continue

        yield line.strip()

def count_address_pairs(url):

    logiter = iter(logfile_lines(url))

    for count, address in zip(logiter, logiter):
        yield (int(count), address)

counts = collections.Counter()

for cnt, addr in count_address_pairs(LOGFILE):
    counts[addr] += cnt

print(counts)

输出看起来很简单:

^{pr2}$

相关问题 更多 >