假设apache日志格式为:
118.78.199.98--[09/Jan/2010:00:59:59+0800]"GET/Public/Css/index.cssHTTP/1.1"304-"http://www.a.cn/common/index.php""Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;GTB6.3)"
问题1:在apachelog中找出访问次数最多的10个IP。
awk'{print$1}'apache_log|sort|uniq-c|sort-nr|head
awk首先将每条日志中的IP抓出来,如日志格式被自定义过,可以-F定义分隔符和print指定列;
sort进行初次排序,为的使相同的记录排列到一起;
upiq-c合并重复的行,并记录重复次数。
head进行前十名筛选;
sort-nr按照数字进行倒叙排序。
我参考的命令是:
显示10条最常用的命令
sed-e"s/|/\n/g"~/.bash_history|cut-d''-f1|sort|uniq-c|sort-nr|head
问题2:在apache日志中找出访问次数最多的几个分钟。
awk'{print$4}'apache.log|cut-c14-18|sort|uniq-c|sort-nr|head
awk用空格分出来的第四列是[09/Jan/2010:00:59:59;
cut-c提取14到18个字符
剩下的内容和问题1类似。
问题3:在apache日志中找到访问最多的页面:
awk'{print$11}'apache_log|sed's/^.*cn\(.*\)\"/\1/g'|sort|uniq-c|sort-rn|head
类似问题1和2,唯一特殊是用sed的替换功能将"http://www.a.cn/common/index.php"替换成括号内的内容:"http://www.a.cn(/common/index.php)"
问题4:在apache日志中找出访问次数最多(负载最重)的几个时间段(以分钟为单位),然后在看看这些时间哪几个IP访问的最多?
版本1
#!/bin/bash
#analysisapacheaccesslog
#histroy
#caoyamengversion0.12010/01/24
if(test-z$1);then
read-p"Specifylogfile:"LOG
else
LOG=$1
fi
if[!-e$LOG];then
echo"Icann'tfindapachelogfile."
exit0
fi
awk'{print$4}'$LOG|cut-c14-18|sort|uniq-c|sort-nr|head>timelog
foriin`awk'{print$2}'timelog`
do
all=`grep$itimelog|awk'{print$1}'`
echo"$i$all"
IP=`grep$i$LOG|awk'{print$1}'|sort|uniq-c|sort-nr|head`
echo"$IP"
done
rm-ftimelog
另一个版本的解决方法,其实就是换了下for的计算方式
#!/bin/bash
#analysisapacheaccesslog
#histroy
#caoyamengversion0.22010/01/24
if(test-z$1);then
read-p"Specifylogfile:"LOG
else
LOG=$1
fi
if[!-e$LOG];then
echo"Icann'tfindapachelogfile."
exit0
fi
awk'{print$4}'$LOG|cut-c14-18|sort|uniq-c|sort-nr|head>timelog
for((i=1;i<=10;i=i+1))
do
num=`sed-n"${i}p"timelog|awk'{print$1}'`
time=`sed-n"${i}p"timelog|awk'{print$2}'`
echo"####TheNo.$i"
echo""
echo"$time$num"
echo""
full=`grep$time$LOG|awk'{print$1}'|sort|uniq-c|sort-nr|head`
echo"$full"
echo""
done
rm-ftimelog
转载于linuxtone网站