【问题标题】:How to get a sum of occurrences of the IP addresses found in access.log如何获取在 access.log 中找到的 IP 地址的总和
【发布时间】:2022-01-22 20:50:37
【问题描述】:

我正在尝试获取在 nginx access.log 中找到的 IP 地址的具体出现次数。 access.log格式如下

xxx.xxx.xxx.xxx - - [21/Dec/2021:12:59:30 +0100] "GET /<some/path/on/webserver>" 200 1028 "<referrer>" "Mozilla/5.0 (Linux; Android 11; SM-A202F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.104 Mobile Safari/537.36" "-"

我目前使用的awk是

awk '$7 ~ /^\/rest\/default\/V1\/products-render-info?/ {print $1, $5}' /var/log/nginx/access.log.1 | sort -u > test.txt

并且保存在文本文件中的结果是,只有唯一的 IP 地址,

127.0.0.1 
/rest/default/V1/products-render-info?searchCriteria.... <snip>

但是,我想知道 IP 地址的出现次数以及类似

127.0.0.1
<number of times this IP address has been found in the access.log>
/rest/default/V1/products-render-info?searchCriteria.... <snip>

非常感谢任何帮助!

谢谢

【问题讨论】:

    标签: nginx awk grep


    【解决方案1】:
    grep "^[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+" test.txt | awk -F" " '{print $1}' | sort | uniq -c
    

    ???原谅我?

    好吧,让我们从正则表达式开始:

    ^       : beginning of line
    [0-9]\+ : a list of digits (at least one)
    \.      : a dot
    

    因此,您的行应该以行首(很明显)开头,然后是至少一个数字、一个点、...的列表,这四次(但末尾没有点)。

    这样你就找到了你的 IP 地址。

    然后您解析它,使用空格作为字段分隔符 (awk -F" "),并显示第一列 '{print $1}'

    现在您已经显示了一个您想要计算的 IP 地址列表。

    因此,您首先对它们进行排序 (sort),完成后,计算唯一结果 (uniq -c)。

    很简单,不是吗? :-)

    【讨论】:

    • 感谢您的回复。但是,test.txt 文件只包含唯一的 IP 地址和请求。我想要的是在 access.log 中对它们进行计数,并将它们写入 test.txt 并显示出现次数......就像awk '$7 ~ /^\/rest\/default\/V1\/products-render-info?/ {print $1, $5}' /var/log/nginx/access.log.1 | sort | uniq -c &gt; test.txt 看起来像我想要开始的......基本上“告诉我总和所有 IP 地址出现,其中请求 URL 以 /rest/default/V1/products-render-info 开头并将它们保存到 test.txt"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 2015-06-22
    • 1970-01-01
    • 2021-07-11
    • 2010-12-26
    相关资源
    最近更新 更多