我有一个我正在尝试解析的apache日志文件。我找到了一些不同的方法,包括apachelog,两个答案here和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
答案 0 :(得分:3)
您可以修改列表中正则表达式的第一个组件,以允许以逗号分隔的主机列表。以下适用于您的示例行:
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(',')
获取地址列表。