日志分析工具Awstats實戰之Nginx篇-分析結果動態化

上一篇博文“分析工具Awstats實戰之Nginx篇-分析結果靜態化”介紹了如何將awstats的日志分析信息用靜態頁面來進行顯示,不過顯示效果肯定沒有動態的好啦。本篇博文將帶大家一起來部署動態的分析結果查閱。


環境:

CentOS 6.4
ip:192.168.1.113
域名:www.sunsky.com(server和client都通過hosts文件解析)
nginx-1.2.9 編譯安裝,路徑/usr/local/nginx,服務開啟狀態
日志記錄格式為nginx默認的,切勿更改,否則會造成awstats無法分析日志。
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';
awstats-7.2.tar.gz CPAN-2.00.tar.gz FCGI-0.74.tar.gz FCGI-ProcManager-0.24.tar.gz
必須有perl-devel,不然無法編譯FCGI。

一、日志自動切割

對于nginx的日志切割,由于沒有像apache一樣去用cronolog工具,這里我們就寫一個腳本,讓它可以在每天00:01自動執行,切割昨天的日志(交由awstats分析),壓縮前天的日志(壓縮日志可減小存儲空間,為防止awstats沒有分析完就被壓縮,所以只壓縮前天的日志)。

vim /server/scripts/cut_nginx_log.sh

輸入以下內容:

#!/bin/sh
yesterday=`date -d "yesterday" +"%Y%m%d"`
before_yesterday=`date -d "-2 day" +"%Y%m%d"`
Nginx_Dir="/usr/local/nginx"
Nginx_logs="/app/logs"
Log_Name="www_access"
cd /tmp
[ -d $Nginx_Logs ] && cd $Nginx_logs || exit 1
[ -f $Log_Name.log ] && /bin/mv $Log_Name.log ${Log_Name}_${yesterday}.log || exit 1
if [ $? -eq 0 -a -f $Nginx_Dir/logs/nginx.pid ]
    then
       kill -USR1 `cat $Nginx_Dir/logs/nginx.pid`
fi
[ -f  ${Log_Name}_${before_yesterday}.log ] && /usr/bin/gzip ${Log_Name}_${before_yesterday}.log|| exit 1

執行crontab -e將該腳本加入定時任務中

1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1

這樣每天凌晨00:01就能自動實現日志的切割,壓縮等功能了。

因為本次實驗下的nginx此時已經有日志了,另外為了后文awstats能對切割過的日志進行分析,所以這里我們要運行一下此腳本,來將現有日志進行切割生成昨天的日志方便后文操作。

/bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1

二、配置FCGI

1、安裝CPAN

wget http://search.cpan.org/CPAN/authors/id/A/AN/ANDK/CPAN-2.00.tar.gz
tar zxf CPAN-2.00.tar.gz
cd CPAN-2.00
perl Makefile.PL
make && make install

2、安裝FCGI和FCGI::ProcManager

wget http://search.cpan.org/CPAN/authors/id/F/FL/FLORA/FCGI-0.74.tar.gz
tar zxf FCGI-0.74.tar.gz
cd FCGI-0.74
第一種安裝方法:perl -MCPAN -e 'install FCGI'
第二種安裝方法:perl Makefile.PL
                make&&make install
wget http://search.cpan.org/CPAN/authors/id/B/BO/BOBTFISH/FCGI-ProcManager-0.24.tar.gz
tar zxf FCGI-ProcManager-0.24.tar.gz
cd FCGI-ProcManager-0.24
第一種安裝方法:perl -MCPAN -e 'install FCGI::ProcManager'
第二種安裝方法:perl Makefile.PL
                make&&make install

在執行第一種安裝方法的時候,一定是全程自動滾動下來提示OK的。如果出現提示你輸入yes之類的,你需要按提示操作完之后,再運行第二次直到全程自動滾動下來提示OK才為完成安裝?;蛘吣憔陀玫诙N方法來執行安裝。

3、創建FCGI啟動文件

vi /usr/local/nginx/sbin/fcgi       #此處按個人習慣命名
#!/usr/bin/perl
use FCGI;
#perl -MCPAN -e 'install FCGI'
use Socket;
use POSIX qw(setsid);
#use Fcntl;
require 'syscall.ph';
&daemonize;
#this keeps the program alive or something after exec'ing perl scripts
END() { } BEGIN() { }
*CORE::GLOBAL::exit = sub { die "fakeexit\nrc=".shift()."\n"; };
eval q{exit};
if ($@) {
        exit unless $@ =~ /^fakeexit/;
};
&main;
sub daemonize() {
    chdir '/'                 or die "Can't chdir to /: $!";
    defined(my $pid = fork)   or die "Can't fork: $!";
    exit if $pid;
    setsid                    or die "Can't start a new session: $!";
    umask 0;
}
sub main {
        #$socket = FCGI::OpenSocket( "127.0.0.1:8999", 10 );
        $socket = FCGI::OpenSocket( "/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock", 10 );
#use UNIX sockets - user running this script must have w access to the 'nginx' folder!!
        $request = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%req_params, $socket );
        if ($request) { request_loop()};
            FCGI::CloseSocket( $socket );
}
sub request_loop {
        while( $request->Accept() >= 0 ) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
           #processing any STDIN input from WebServer (for CGI-POST actions)
           $stdin_passthrough ='';
           $req_len = 0 + $req_params{'CONTENT_LENGTH'};
           if (($req_params{'REQUEST_METHOD'} eq 'POST') && ($req_len != 0) ){
                my $bytes_read = 0;
                while ($bytes_read < $req_len) {
                        my $data = '';
                        my $bytes = read(STDIN, $data, ($req_len - $bytes_read));
                        last if ($bytes == 0 || !defined($bytes));
                        $stdin_passthrough .= $data;
                        $bytes_read += $bytes;
                }
            }
            #running the cgi app
            if ( (-x $req_params{SCRIPT_FILENAME}) && #can I execute this?
                 (-s $req_params{SCRIPT_FILENAME}) && #Is this file empty?
                 (-r $req_params{SCRIPT_FILENAME})     #can I read this file?
            ){
                pipe(CHILD_RD, PARENT_WR);
                my $pid = open(KID_TO_READ, "-|");
                unless(defined($pid)) {
                        print("Content-type: text/plain\r\n\r\n");
                        print "Error: CGI app returned no output - Executing $req_params
{SCRIPT_FILENAME} failed !\n";
                        next;
                }
                if ($pid > 0) {
                        close(CHILD_RD);
                        print PARENT_WR $stdin_passthrough;
                        close(PARENT_WR);
                        while(my $s = <KID_TO_READ>) { print $s; }
                        close KID_TO_READ;
                        waitpid($pid, 0);
                } else {
                        foreach $key ( keys %req_params){
                           $ENV{$key} = $req_params{$key};
                        }
                        # cd to the script's local directory
                        if ($req_params{SCRIPT_FILENAME} =~ /^(.*)\/[^\/]+$/) {
                                chdir $1;
                        }
                        close(PARENT_WR);
                        close(STDIN);
                        #fcntl(CHILD_RD, F_DUPFD, 0);
                        syscall(&SYS_dup2, fileno(CHILD_RD), 0);
                        #open(STDIN, "<&CHILD_RD");
                        exec($req_params{SCRIPT_FILENAME});
                        die("exec failed");
                }
            }
            else {
                print("Content-type: text/plain\r\n\r\n");
                print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is
not executable by this process.\n";
            }
        }
}

創建完成后,需要賦予fcgi執行權限:

chmod 755 /usr/local/nginx/sbin/fcgi

啟動FPM(FastCGI 進程管理器)

perl /usr/local/nginx/sbin/fcgi >/dev/null 2>&1

在這里,Nginx需要對fcgi生成的/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock有讀寫權限,否則會報502錯誤。

三、Awstats的安裝與配置

1、部署awstats

首先我們要下載awstats軟件包,并將其放在常規目錄(/usr/local)下

wget http://awstats.sourceforge.net/files/awstats-7.2.tar.gz
tar zxf awstats-7.2.tar.gz
mv awstats-7.2 /usr/local/awstats

由于wget下載下來的包中權限是非root的,所以這里要修改權限,否則稍后*.pl將無法運行

chown -R root.root /usr/local/awstats
chmod +x /usr/local/awstats/tools/*.pl
chmod +x /usr/local/awstats/wwwroot/cgi-bin/*.pl

接下來我們要執行awstats/tools下的awstats_configure.pl配置向導,用來生成awstats的配置文件,awstats配置文件的命名規則是awstats.website.conf

cd /usr/local/awstats/tools/
./awstats_configure.pl

此時會出現如下提示

----- AWStats awstats_configure 1.0 (build 1.9) (c) Laurent Destailleur -----
This tool will help you to configure AWStats to analyze statistics for
one web server. You can try to use it to let it do all that is possible
in AWStats setup, however following the step by step manual setup
documentation (docs/index.html) is often a better idea. Above all if:
- You are not an administrator user,
- You want to analyze downloaded log files without web server,
- You want to analyze mail or ftp log files instead of web log files,
- You need to analyze load balanced servers log files,
- You want to 'understand' all possible ways to use AWStats...
Read the AWStats documentation (docs/index.html).
-----> Running OS detected: Linux, BSD or Unix
-----> Check for web server install
Enter full config file path of your Web server.
Example: /etc/httpd/httpd.conf
Example: /usr/local/apache2/conf/httpd.conf
Example: c:\Program files\apache group\apache\conf\httpd.conf
Config file path ('none' to skip web server setup):
> none      #這里讓填寫網頁服務器的配置文件路徑,因為我們用的不是apache,所以這里要填none
Your web server config file(s) could not be found.
You will need to setup your web server manually to declare AWStats
script as a CGI, if you want to build reports dynamically.
See AWStats setup documentation (file docs/index.html)
-----> Update model config file '/usr/local/awstats/wwwroot/cgi-bin/awstats.model.conf'
  File awstats.model.conf updated.
-----> Need to create a new config file ?
Do you want me to build a new AWStats config/profile
file (required if first install) [y/N] ? y         #詢問是否創建一個新的配置文件,這里填y
-----> Define config file name to create
What is the name of your web site or profile analysis ?
Example: www.mysite.com
Example: demo
Your web site, virtual server or profile name:
> www.sunsky.com      #這里讓填寫你的網站域名,虛擬主機名或者隨便一個配置名
-----> Define config file path
In which directory do you plan to store your config file(s) ?
Default: /etc/awstats
Directory path to store config file(s) (Enter for default):
>              #這里要填寫你配置文件存放路徑,我們使用它默認的路徑/etc/awstats,所以直接回車即可
-----> Create config file '/etc/awstats/awstats.www.sunsky.com.conf'
 Config file /etc/awstats/awstats.www.sunsky.com.conf created.
-----> Add update process inside a scheduler
Sorry, configure.pl does not support automatic add to cron yet.
You can do it manually by adding the following command to your cron:
/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com
Or if you have several config files and prefer having only one command:
/usr/local/awstats/tools/awstats_updateall.pl now
Press ENTER to continue...   #提示不能自動加入crontab定時任務,需要稍后自己添加,我們按回車繼續即可
A SIMPLE config file has been created: /etc/awstats/awstats.www.sunsky.com.conf
You should have a look inside to check and change manually main parameters.
You can then manually update your statistics for 'www.sunsky.com' with command:
> perl awstats.pl -update -config=www.sunsky.com
You can also build static report pages for 'www.sunsky.com' with command:
> perl awstats.pl -output=pagetype -config=www.sunsky.com
Press ENTER to finish... #提示配置文件創建完成和如何更新配置及建立靜態報告頁,這里我們回車即可結束這個配置向導

2、修改awstats配置文件

完成配置文件的創建之后,我們還需要對/etc/awstats/awstats.www.sunsky.com.conf里的一些參數進行修改。

sed -i 's#LogFile="/var/log/httpd/mylog.log"#LogFile="/app/logs/www_access_%YYYY-24%MM-24%DD-24.log"#g' /etc/awstats/awstats.www.sunsky.com.conf

這里更改的目的是指定awstats需要分析的nginx的日志文件路徑。這里的路徑大家要按自己的日志路徑來填。

sed -i 's#DirData="/var/lib/awstats"#DirData="/usr/local/awstats/data"#g' /etc/awstats/awstats.www.sunsky.com.conf

這里更改的目的是指定awstats的數據庫配置文件(即awstats的數據庫(純文本))。

由于,此處沒有/usr/local/awstats/data目錄,所以我們要創建出來

mkdir /usr/local/awstats/data

以上的兩個替換操作進行完之后一定要用命令查看替換是否成功,以便及早發現紕漏。

grep "LogFile=" /etc/awstats/awstats.www.sunsky.com.conf
grep "DirData=" /etc/awstats/awstats.www.sunsky.com.conf

查詢替換結果正確之后,即可進行下面的步驟。

3、生成awstats統計信息數據庫

現在我們需要用awstats來生成對日志的統計分析信息出來了。由于我們用的是支持perl的FCGI動態化訪問頁面,所以此處我們只需要直接更新數據庫即可。FCGI程序會自動將數據庫以動態頁面的形式展現出來,無須再手動生成靜態頁面了。本處我們用腳本來完成。

vim /server/scripts/awstats_up.sh
#!/bin/sh
/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=www.sunsky.com >/dev/null 2>&1

該腳本里面用下面的命令也是可以的。

/usr/local/awstats/tools/awstats_updateall.pl now

運行該腳本生成分析結果

/bin/sh /server/scripts/awstats_up.sh

四、配置日志分析頁面的來訪ip的地址位置顯示

這里我們用國內最準確的ip數據庫——QQ純真庫(點擊下載),大家下載之后通過CRT用lrzsz工具傳上去,具體步驟這里不寫了。

附件里面有三個文件qqhostinfo.pm,qqwry.pl和QQWry.Dat,我們將這三個文件統統都放到/usr/local/awstats/wwwroot/cgi-bin/plugins中。

接下來,我們修改qqwry.pl文件,將./QQWry.Dat修改為${DIR}/plugins/QQWry

vim /usr/local/awstats/wwwroot/cgi-bin/plugins/qqwry.pl
 #my $ipfile="./QQWry.Dat";

修改為

my $ipfile="${DIR}/plugins/QQWry.Dat ";

然后編輯awstats的配置文件/etc/awstats/awstats.www.sunsky.com.conf(根據你前面配置的站點信息生成的文件),將LoadPlugin="hostinfo"替換為LoadPlugin="qqhostinfo"即可。

sed -i 's#\#LoadPlugin="hostinfo"#LoadPlugin="qqhostinfo"#g' /etc/awstats/awstats.www.sunsky.com.conf

切記,在這些替換完之后一定要查看替換是否成功,以便及早發生紕漏。

grep "LoadPlugin=\"qqhostinfo\"" /etc/awstats/awstats.www.sunsky.com.conf

如果檢查無誤,那么我們的ip地址位置顯示就配置好了,在后面的日志分析中,我們就可以清楚的看到來訪ip的地理位置信息了。


五、配置nginx

接下來我們要配置nginx使其能安全的訪問到分析的數據

vim /usr/local/nginx/conf/nginx.conf

在server{}內添加如下內容:

server {
           listen 80;
           server_name www.sunsky.com;
            location / {
            root   /www/sunsky;
            index  index.html index.htm;
            access_log  /app/logs/www_access.log  main;
    }
            location ~* ^/cgi-bin/.*\.pl$ {
            root /usr/local/awstats/wwwroot;
               fastcgi_pass unix:/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock;
               fastcgi_index index.pl;
               include  fastcgi_params;
               charset gb2312;
               auth_basic "Restricted";       #有些網站不愿意公開網站流量信息,所以加個認證
               auth_basic_user_file /usr/local/nginx/htpasswd.pass;  #該文件由apache的加密認證工具htpasswd創建
           }
      location ~ ^/icon/ {
         root   /usr/local/awstats/wwwroot/;
         index index.html;
         access_log off;
         error_log off;
         charset gb2312;
      }
}

為了保持nginx.conf主配置文件更加整潔干凈,所以我們將fastcgi_param的一系列參數添加到/usr/local/nginx/conf/fastcgi_params文件的最頂部,然后在nginx.conf里面調用這個文件即可。

vi /usr/local/nginx/conf/fastcgi_params
               fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
               fastcgi_param QUERY_STRING     $query_string;
               fastcgi_param REQUEST_METHOD   $request_method;
               fastcgi_param CONTENT_TYPE     $content_type;
               fastcgi_param CONTENT_LENGTH   $content_length;
               fastcgi_param GATEWAY_INTERFACE CGI/1.1;
               fastcgi_param SERVER_SOFTWARE    nginx;
               fastcgi_param SCRIPT_NAME        $fastcgi_script_name;
               fastcgi_param REQUEST_URI        $request_uri;
               fastcgi_param DOCUMENT_URI       $document_uri;
               fastcgi_param DOCUMENT_ROOT      $document_root;
               fastcgi_param SERVER_PROTOCOL    $server_protocol;
               fastcgi_param REMOTE_ADDR        $remote_addr;
               fastcgi_param REMOTE_PORT        $remote_port;
               fastcgi_param SERVER_ADDR        $server_addr;
               fastcgi_param SERVER_PORT        $server_port;
               fastcgi_param SERVER_NAME        $server_name;
               fastcgi_read_timeout 60;

針對上面的加密,由于nginx沒有好的加密認證工具,需要借助apache的htpasswd來實現加密認證功能

htpasswd -c -m /usr/local/nginx/htpasswd.pass sunskyadmin      #用戶名為sunskyadmin

配置完畢之后,檢查nginx語法,然后優雅重啟之后,用游覽器訪問http://www.sunsky.com/cgi-bin/awstats.pl?config=www.sunsky.com,輸入賬號密碼之后即可查看統計信息了。

至此,awstats已經可以實現對Nginx的日志統計,動態化安全訪問及來訪ip的地址位置顯示等功能了。

1.png

2.png

五、配置awstats自動運行

為了讓整個日志的統計過程可以實現自動化,將awstats.sh腳本加入crontab定時任務中去,此時結合上面的定時切割任務,我們的crontab里面會有多出來兩條定時任務

1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
0 1 * * * /bin/sh /server/scripts/awstats_up.sh >/dev/null 2>&1

到此,我們整個日志訪問工具awstats在nginx上對日志分析之后的靜態化和動態化訪問都已經實現了。后面的話,我會再寫一篇awstats對apache服務器的日志分析部署文檔。大家如果有什么問題的話,可以聯系我進行交流探討,咱們共同學習,共同進步!

轉自:http://nolinux.blog.51cto.com/4824967/1317429

原創文章,作者:s19930811,如若轉載,請注明出處:http://www.www58058.com/2020

(0)
s19930811s19930811
上一篇 2016-08-15
下一篇 2016-08-15

相關推薦

  • 馬哥教育網絡班21期+第7周課程練習

    1、創建一個10G分區,并格式為ext4文件系統; (1) 要求其block大小為2048, 預留空間百分比為2, 卷標為MYDATA, 默認掛載屬性包含acl; [root@localhost ~]#mke2fs -t ext4 -b 2048 -m 2 -L &qu…

    Linux干貨 2016-08-15
  • 16個很有用的在線工具

    1. ExplainShell.com 命令解釋 對于Linux用戶來說每天都會寫各種命令和腳本,那么你可以使用這個網站工具來查看命令式如何工作的,這樣可以避免不必要的錯誤出現;也是一個很好的學習命令的方式 2. BashrcGenerator.com 定制個性命令提示符 簡單說就是個性化生成命令提示符,可將生成的代碼…

    Linux干貨 2015-03-13
  • 運維學習筆記-看看別人家的Puppet代碼

    這篇博客的目的是通過分析Forge上的Puppet模塊來加深一些概念的理解,同時了解一些常用用法。 今天的例子是jfryman-nginx模塊,它是原puppetlabs-nginx模塊的升級版本,依賴3個Puppet公共模塊:puppetlabs-apt,puppetlabs-stdlib和puppetlabs-concat。安裝非常方便,puppet m…

    Linux干貨 2016-06-23
  • 常用命令總結

    ifconfig查看IP地址 date查看日期和時間 cd跳轉到任何目錄 useradd新建一個普通用戶 passwd給用戶設置密碼 poweroff   halt    關機 reboot  重啟 cal  查看日歷 cal -y 查看一年日歷 env  export&nbsp…

    Linux干貨 2017-04-04
  • 馬哥linux運維26期開班感悟

         今天的收獲,有以下幾點      1.自己的公眾演說能力很弱,要多多練習,給自己更多的機會。     2.自己想提升自己的心很強,但是自己卻不知道該怎么做?     3.即便學完了也只是一個開始,希望自己有一顆歸零的心態。

    Linux干貨 2017-07-10
  • 日志分析工具Awstats實戰之Nginx篇-分析結果靜態化

    原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原始出處 、作者信息和本聲明。否則將追究法律責任。http://nolinux.blog.51cto.com/4824967/1316979 前言: Awstats 是在 SourceForge 上發展很快的一個基原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原始出處…

    Linux干貨 2016-08-15

評論列表(1條)

  • lgljfy
    lgljfy 2016-08-15 15:31

    fastcgi_pass unix:/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sock 這個文件是怎么生成的

欧美性久久久久