如果發現伺服器有大量存取記錄, 要檢查是否 DDOS 攻擊, 可以開啟記錄檔檢查, 但資料量大的話, 要人手檢查也很困難, 所以我寫了這個簡單的 Perl Script, 用作檢查記錄檔內出現次數最多的 IP, 鎖定出現頻率最高的 IP 作檢查會容易得多。
編寫時想到有多種記錄檔也有此需要, 只要記錄檔是一行一個記錄, 而每行只有一個 IP 出現便可以用, 已經試過 apache access log 及 error log, /var/log/secure, /var/log/vsftpd.log 也可以正確使用。執行速度尚算可以, 檢查一個 350MB 的 apache log, 使用 raid1 的伺服器需時大約 6 秒。
使用方法為: count_ip.pl log_file [count]
例如我想檢查 apache log, 記錄檔在/var/log/httpd/access.log, 是這樣:
./count_ip.pl /var/log/httpd/access.log
預設會顯示頭 10 個出現最多的 IP, 如果想顯示更多 IP 也可以自訂, 例如想顯示 20 個 IP:
./count_ip.pl /var/log/httpd/access.log 20
如果想儲存結果的話, 可以這樣:
./count_ip.pl /var/log/httpd/access-20150416.log > /var/log/ip_count_result.log
這樣結果便會儲存在 /var/log/ip_count_result.log
#!/usr/bin/perl ############################################################################### # Name: count_ip.pl # Author: Sam Tang # Website: http://www.phpini.com/ # Purpose: read log file and print a report, display top tarffic ip, the ip # total access times and total access. ############################################################################### use strict; use warnings; no warnings 'numeric'; # disable Argument "XXX" isn't numeric warning my $line_num = 10; ### default show top 10 records if (!$ARGV[0]) { die "Usage: count_ip.pl logfile [display lines] "; } my $log = $ARGV[0]; $line_num = $ARGV[1] if ($ARGV[1]); ##### open log file, get the hostname and traffic open(my $fh, '<', $log) or die "Could not open file '$log' $!"; my %ip; my $total = 0; ##### save ip data to %ip while (my $row = <$fh>) { if( $row =~ /(d{1,3}.d{1,3}.d{1,3}.d{1,3})/ ){ $ip{$1}++; $total++; } } ##### print top ip report print "================================== "; print " << IP Traffic Report: >> ================================== "; my $start = 0; foreach my $host (reverse sort { $ip{$a} <=> $ip{$b} } keys %ip) { if ($start < $line_num) { print $start+1 . "."; ### print order number print " " if $start < 9; ### add space for left align print " $host: $ip{$host} "; ### print data } $start++; } print "================================== "; print " Total Access: $total "; print "================================== ";
下載後確定第 1 行是伺服器上面 perl 的路徑, 加入可執行權限便以使用了。
转载请注明:我是IT » [Perl Script] 統計記錄檔 IP