環境:
CentOS 6.4
ip192.3
ドメイン名:www.sunsky.com(serverとクライアントは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をコンパイルできない。
I. 丸太の自動切断
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
これにより、毎日午前0時1分にログのカットや圧縮などが自動化されます。
/bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
#p#
FCGIの設定
1.CPANのインストール
wget http://..org/CPAN/authors/id/A/AN/ANDK/CPAN-...gz
tar zxf CPAN-2.00.tar.gz
cd CPAN-2.00
perl Makefile.PL
make && make install
2.FCGIとFCGI::ProcManagerをインストールします。
wget http://..org/CPAN/authors/id/F/FL/FLORA/FCGI-...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://..org/CPAN/authors/id/B/BO/BOBTFISH/FCGI-ProcManager-...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が出るまで2回目を実行してインストールを完了する必要があります。または、2番目の方法でインストールを実行することもできます。
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
rc=".shift()."
"; };
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( ".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
");
print "Error: CGI app returned no output - Executing $req_params
{SCRIPT_FILENAME} failed !
";
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
");
print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not exist or is
not executable by this process.
";
}
}
}
作成したら、fcgi に実行権限を与える必要があります:
chmod 755 /usr/local/nginx/sbin/fcgi
スタートFPM
perl /usr/local/nginx/sbin/fcgi >/dev/null 2>$1
ここで、Nginxはfcgiによって生成された/usr/local/nginx/fastcgi_temp/perl_cgi-dispatch.sockに読み書きできる必要があります。
#p#
III.Awstatsのインストールと設定
1.awstatsのデプロイ
最初にすることは、awstatsパッケージをダウンロードして、通常のディレクトリに置くことです:
wget http://..net/files/awstats-...gz
tar zxf awstats-7.2.tar.gz
mv awstats-7.2 /usr/local/awstats
wgetでダウンロードしたパッケージのパーミッションはnon-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
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 #ここでは、ウェブサーバの設定ファイルのパスを記入しよう。
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のタイマータスクに参加することはできません、あなたは後で自分自身を追加する必要があり、Enterキーを押して続けることができる
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/awstatswww.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のデータベース・プロファイルを指定することです。
usr/local/awstats/dataディレクトリがないので、作成します:
mkdir /usr/local/awstats/data
上記の2つの置き換えが行われた後、エラーを早期に発見するために、置き換えが成功したかどうかを確認するコマンドを必ず使用してください。
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
#p#
訪問ipのアドレス位置を表示するログ分析ページの設定
次に、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 ";
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の地理的な位置情報を明確に見ることができます。
V. 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 設定ファイルをすっきりさせるために、/usr/local/nginx/conf/fastcgi_params ファイルの先頭に fastcgi_param のパラメータリストを追加し、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://。/-/.?/-/.?.omにアクセスし、アカウントのパスワードを入力すると、統計情報を見ることができます。
この時点で、awstatsはNginxのログ統計、動的セキュリティアクセス、訪問ipアドレス位置表示などの機能を実装することができました。
V. awstatsの自動実行設定
ログ統計処理全体を自動化するために、awstats.shスクリプトをcrontabの時限タスクに追加します。この時、上記の時限カットタスクと合わせて、crontabにはさらに2つの時限タスクが追加されます。
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
ここまでで、静的・動的アクセス後のnginxログ解析におけるログアクセスツールawstatsの全体像が見えてきました。後で、私は別のawstatsのapacheサーバのログ解析の展開文書を書く予定です。何か質問があれば、私に連絡して議論を交わし、共に学び、共に進歩しましょう!





