对于 this issue我正在尝试创建一个 grok 模式,它与 nginx 日志中 X-Forwarded-For header 中的第一个 IP 匹配。
日志行通常如下所示:
68.75.44.178, 172.68.146.54, 127.0.0.1 - - [15/May/2017:12:16:27 +0200] "GET /jobs/24237/it-back-end HTTP/1.1" 301 5 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
第一个 IP 是客户端的实际 IP,这是我想要检索的 IP,另外两个来自代理,在我们的例子中是 cloudflare 和 varnish。
我试过的模式 https://grokconstructor.appspot.com看起来像这样:
FIRSTIPORHOST (^%{IPORHOST})(?:,\s%{IPORHOST})*
不幸的是,它匹配所有 IP,尽管没有捕获组,那我做错了什么?或者有更好的模式吗?
澄清:
使用 filebeats 将整个日志文件读入 Elasticsearch ,因此我需要以某种方式匹配 IP,否则我将无法匹配该行的其余部分,例如日期或用户代理等。
最佳答案
您需要添加 (?:,\s[\d.]+)*
后 %{IPORHOST:nginx.access.remote_ip}
在模式的开头。见固定表达式:
"%{IPORHOST:nginx.access.remote_ip}(?:,\\s[\\d.]+)* - %{DATA:nginx.access.user_name} \\[%{HTTPDATE:nginx.access.time}\\] \"%{WORD:nginx.access.method} %{DATA:nginx.access.url} HTTP/%{NUMBER:nginx.access.http_version}\" %{NUMBER:nginx.access.response_code} %{NUMBER:nginx.access.body_sent.bytes} \"%{DATA:nginx.access.referrer}\" \"%{DATA:nginx.access.agent}\""
(?:,\s[\d.]+)*
非捕获重复组匹配 0+ 次出现:,
- 逗号 \s
- 空格 [\d.]+
- 1+ 位数字或逗号。 这样,就无法捕获额外的数据。
关于regex - Grok/Oniguruma 模式匹配来自 X-Forwarded-For header 的第一个 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047463/