上一篇博文「分析工具Awstats實戰之Nginx篇-分析結果靜態化」介紹瞭如何將awstats的日誌分析信息用靜態頁面來進行顯示,不過顯示效果確定沒有動態的好啦。本篇博文將帶你們一塊兒來部署動態的分析結果查閱。html
環境:nginx
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。
1、日誌自動切割
web
對於nginx的日誌切割,因爲沒有像apache同樣去用cronolog工具,這裏咱們就寫一個腳本,讓它能夠在天天00:01自動執行,切割昨天的日誌(交由awstats分析),壓縮前天的日誌(壓縮日誌可減少存儲空間,爲防止awstats沒有分析完就被壓縮,因此只壓縮前天的日誌)。數據庫
vim /server/scripts/cut_nginx_log.sh
輸入如下內容:apache
#!/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將該腳本加入定時任務中vim
1 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
這樣天天凌晨00:01就能自動實現日誌的切割,壓縮等功能了。
安全
由於本次實驗下的nginx此時已經有日誌了,另外爲了後文awstats能對切割過的日誌進行分析,因此這裏咱們要運行一下此腳本,來將現有日誌進行切割生成昨天的日誌方便後文操做。bash
/bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
2、配置FCGI
服務器
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
二、安裝FCGI和FCGI::ProcManagersession
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才爲完成安裝。或者你就用第二種方法來執行安裝。
三、建立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錯誤。
3、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... #提示配置文件建立完成和如何更新配置及創建靜態報告頁,這裏咱們回車便可結束這個配置嚮導
二、修改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
mkdir /usr/local/awstats/data
以上的兩個替換操做進行完以後必定要用命令查看替換是否成功,以便及早發現紕漏。
grep "LogFile=" /etc/awstats/awstats.www.sunsky.com.conf grep "DirData=" /etc/awstats/awstats.www.sunsky.com.conf
查詢替換結果正確以後,便可進行下面的步驟。
三、生成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
4、配置日誌分析頁面的來訪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的地理位置信息了。
5、配置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的地址位置顯示等功能了。
5、配置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