今天主要讲述一下apache和nginx服务器日志的管理和查询操作。
有时候运维需要分析网站日志数据分析,在这么多的日志里面如何快速找到想要的ip以及有用信息。
这就需要技术的手段,脚本程序运行帮助查找了。
下面介绍如何知道日志的ip地址的分布地区,如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #!/bin/sh time=`date +%Y-%m-%d_%H-%M-%S` #这里可以是nginx日志,本教程是apache日志为例 filepath=/var/log/httpd/ssl_access_log #如果log格式文件,txt防止轮询压缩 shorttimefile=/var/log/httpd/shorttimeipstore.txt #得到文件内容赋值变量但是字符串 cat ${filepath} | awk '/\s/{print $1}' |sort|uniq -c|sort -rn > ${shorttimefile} for i in `cat ${shorttimefile}|awk '/\s/{print $2}'` do getdata=$(curl http://ip.taobao.com/service/getIpInfo.php?ip=${i}|sed -e 's/.*data\":{\(.*\),\"county\".*/\1/g') if [[ ${getdata} =~ 'DOCTYPE' ]] then continue fi getipnum=$(cat ${shorttimefile}|grep -w ${i}|awk '/\s/{print $1}') #找到了就执行 if [[ ${getipnum} > 0 ]] then if [[ ${getdata} == '' ]] then sleep 1 #利用淘宝的查询IP地址地区查询 getdata=$(curl http://ip.taobao.com/service/getIpInfo.php?ip=${i}|sed -e 's/.*data\":{\(.*\),\"county\".*/\1/g') if [[ ${getdata} == '' ]] then sleep 2 getdata=$(curl http://ip.taobao.com/service/getIpInfo.php?ip=${i}|sed -e 's/.*data\":{\(.*\),\"county\".*/\1/g') fi fi echo "\"num\":\""${getipnum}"\","${getdata} >> /var/log/httpd/IParea${time}.txt fi sleep $(($RANDOM%3+1 )) done if [[ -f ${shorttimefile} ]]; then rm -rf ${shorttimefile} fi |
通过以上可以知道访问你的网站的ip地址归属地。
下面在介绍常见的操作:
第一个查询访问网站的最多的10名的ip地址:
1 | cat /var/log/httpd/access.log | awk '/\s/{print $1}'|sort|uniq -c|sort -rn|awk '{print $0}'|head -n 10 |
第二个查询每天访问网站最多的前10名的ip地址:
1 | cat access.log | awk '/\s/{print $1,$4}'| sed -e 's/^\([0-9]\{1,\}.*\.[0-9]\{1,\}\)\s\{1,\}\[\(.*\)\:[0-9]\{1,\}\:[0-9]\{1,\}\:[0-9]\{1,\}/\1 \2/g'|sort|uniq -c|sort -rn|awk '{print $0}'|head -n 10 |
第三个查询503状态码错误的ip最多访问情况
1 2 3 4 | cat access.log | awk '/\s/{print $1,$9}'|awk '/\s503/{print $1}'|sort|uniq -c|sort -rn #这里503可以换成200 404等其他的状态码,根据自己的需要查询。 |
这里我就简单的介绍下服务器日志常用操作,希望对你有帮助。