3

我有一个我正在尝试解析的 apache 日志文件。我找到了一些不同的方法,包括apachelog 、这里的两个答案和this。使用其中任何一种方法,我都能够解析日志中的大部分行。但是,有些线路有 2 个 IP 地址:

xxx.xx.xx.xxx, yy.yyy.yy.yyy - - [14/Feb/2013:03:55:21 +0000] "GET /alink HTTP/1.0" 200 90210 "http://www.google.com/search" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko; Google Web Preview) Chrome/22.0.1229 Safari/537.4"

提到的方法都不能正确解析这一行。(我什至尝试了 apachelog 的 virtualhost 选项)。有什么建议么?我正在使用我提到的后一种方法(但对任何事情都持开放态度),例如:

parts = [
    r'(?P<host>\S+)',                   # host %h
    r'\S+',                             # indent %l (unused)
    r'(?P<user>\S+)',                   # user %u
    r'\[(?P<time>.+)\]',                # time %t
    r'"(?P<request>.+)"',               # request "%r"
    r'(?P<status>[0-9]+)',              # status %>s
    r'(?P<size>\S+)',                   # size %b (careful, can be '-')
    r'"(?P<referer>.*)"',               # referer "%{Referer}i"
    r'"(?P<agent>.*)"',                 # user agent "%{User-agent}i"
    ]
    pattern = re.compile(r'\s+'.join(parts)+r'\s*\Z')

    for line in open(log):
        try:    
            m = pattern.match(line)
            if m:
                res = m.groupdict()
                data.append(res)
            if not m:
                print line
        except:
            print line
4

1 回答 1

4

您可以修改列表中正则表达式的第一个组件,以允许使用逗号分隔的主机列表。以下适用于您的示例行:

import re
parts = [
    r'(?P<host>\S+(,\s*\S+)*)',         # comma-separated list of hosts                             
    r'\S+',                             # indent %l (unused)                
    r'(?P<user>\S+)',                   # user %u                           
    r'\[(?P<time>.+)\]',                # time %t                           
    r'"(?P<request>.+)"',               # request "%r"                      
    r'(?P<status>[0-9]+)',              # status %>s                        
    r'(?P<size>\S+)',                   # size %b (careful, can be '-')     
    r'"(?P<referer>.*)"',               # referer "%{Referer}i"             
    r'"(?P<agent>.*)"',                 # user agent "%{User-agent}i"       
]
pattern = re.compile(r'\s+'.join(parts)+r'\s*\Z')

test = 'xxx.xx.xx.xxx, yy.yyy.yy.yyy - - [14/Feb/2013:03:55:21 +0000] "GET /alink HTTP/1.0" 200 90210 "http://www.google.com/search" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML,like Gecko; Google Web Preview) Chrome/22.0.1229 Safari/537.4"'
m = pattern.match(test)
res = m.groupdict()

在上述命令之后,res['host']包含xxx.xx.xx.xxx, yy.yyy.yy.yyy. 如果您需要单独的主机地址,您可以使用res['host'].split(',')获取地址列表。

于 2013-02-26T19:17:18.200 回答