Linux小技巧之:两种方法统计访问web网站的前10个IP

 获得访问前10位的IP地址:

[root@manage:~]# cat /var/log/nginx/access.log | awk '{print $1}'|sort|uniq -c | sort -nr | head -10
  10299 10.46.170.7
      4 218.202.70.147
      1 77.72.83.87
      1 5.39.217.107
      1 185.197.74.234
      1 185.197.74.231

 第二种方法:

[root@ELK-chaofeng ~]#cat /var/log/httpd/access_log | awk '{IP[$1]++}END {for (i in IP){ if (IP[i]>=5) {print IP[i],i}}}' | sort -n
5 1.197.190.113
5 80.82.70.187
6 59.36.132.144
8 176.32.33.80
9 124.90.55.182
10 39.98.206.21
64 222.88.236.174

这个例子是我加上了if判断,只有连接数大于5的时候,才会被执行

此外还有一点需要注意:sort中有个-n参数表示以数字进行排序,默认是以每行的第一字段的数值来进行排序的。

也可以格式化显示的整齐一点:

[root@ELK-chaofeng ~]#cat /var/log/httpd/access_log | awk -F' ' '{IP[$1]++}END{for (i in IP) {if (IP[i] >= 5){printf "%-5d  %-15s
",IP[i],i}}}' | sort -rn
136    182.117.204.113
64     222.88.236.174
10     39.98.206.21
9      124.90.55.182
8      176.32.33.80
6      80.82.70.187
6      59.36.132.144
5      1.197.190.113