2009年3月20日星期五

监控统计网站服务器流量的小脚本
















监控统计网站服务器流量的小脚本

最近需要了解一下服务器的流量,看来还是通过apache的日志来操作最为方便和直接,于是有了下面的东东。

1:首先配置apache的日志支持输出io,假设我们把IO的数值放到第一第二列

httpd.conf
    ……
    <IfModule>
      LogFormat "%I %O %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" " combinedio
    </IfModule>
    CustomLog logs/access_log combinedio
    ……

2:编写统计流量的脚本
~ # cat io_log.sh
export LANG=C
DATE_YEAR=`date +%b\\\/%Y`
DATEYEAR=`date +%Y%b`
errDATEmon=`date +%b`
errDATEyear=`date +%Y\\\]`
DAY=`date +%d\/%b\/%Y`
echo -n $DAY, >> /jack/stat//io.csv
#将第一第二列的数据输出到tmp文件
cat /usr/local/apache2/logs/access_log |grep $DAY | awk '{print $1 ","$2}' > /tmp/tmp_io.txt
#用python计算总流量
python ioLog.py >>  /jack/stat//io.csv


~ # cat ioLog.py
if __name__ == '__main__':
    f=open('/tmp/tmp_io.txt')

    inBytes = 0
    outBytes = 0
    for line in f.readlines():
        inB = line[0:line.index(',')]
        outB = line[line.index(',') +1:]

        inBytes += int(inB)
        outBytes += int(outB)

    print '%s,%s,MB' % (inBytes/1024/1024, outBytes/1024/1024)

3:将脚本每天晚上执行,以得到每天的流量
~ # crontab -l
……
58 23 * * * /bin/sh /root/io_log.sh
……

PS:这些东西在awstats里全部都有,只不过如果没有使用的话,这也算是一个山寨统计办法 :-)

没有评论: