用于匹配 Apache2 访问日志中的 GET 请求的正则表达式

RegEx for matching GET request in Apache2 access logs

我想提取在 Apache2 访问日志中找到的 GET 请求中的 URL。

这是我的代码:

import re

x = "192.168.1.137 - - [07/Oct/2020:00:46:13 +0800] "GET /index1.php?command=CON4,0088888 HTTP/1.1" 200 454 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/75.0.564.63""

url = re.search("\/index1\.php\?command=....\,.....", x)
if url:
   print(url.group())
else:
   print("No match found")

当我 运行 这段代码时,它告诉我找不到匹配项,我的正则表达式有问题吗?我是 Regex 的新手,所以非常感谢您的帮助。 我想要得到的确切 URL 是:/index1.php?command=CON4,0088888

您使用的regex不允许您的支票有任何差异。当您使用 . 时,它将匹配任何字符之一。如果长度发生变化,您的正则表达式检查将不准确。


如果所有 uri 都是 index.php 你可以使用

\/index.php([^\s]+)
  • \/index.php - 将准确找到 /index.php
  • ([^\s]+) - 将匹配所有字符直到第一个白色 space

但是,如果这会发生变化,您可以使用以下内容来匹配任何 uri 的不同长度。

(?<=GET )\/(.*).php([^\s]+)
  • (?<=GET ) - 将进行积极的回顾以确认 GET 在我们的 uri
  • 之前存在
  • \/(.*).php([^\s]+) - 将匹配任何以 .php 结尾的 uri,无论长度如何,然后是所有字符,直到第一个白色 space.

import re

x = '192.168.1.137 - - [07/Oct/2020:00:46:13 +0800] "GET /index1.php?command=CON4,0088888 HTTP/1.1" 200 454 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/75.0.564.63"'

url = re.search(r'(?<=GET )\/(.*).php([^\s]+)', x)
if url:
   print(url.group())
else:
   print("No match found")

输出:

#/index1.php?command=CON4,0088888
import re

x = '192.168.1.137 - - [07/Oct/2020:00:46:13 +0800] "PUT /index.php?command=CON4,0088888 HTTP/1.1" 200 454 "-" "Mozilla/5.0 (Windows NT 10.0; Win 64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36 Edg/75.0.564.63"'

url = re.search('.*\s(.*)\sHTTP', x)
if url:
   print(url.group(1))
else:
   print("No match found")

输出:

/index.php?command=CON4,0088888