#!/usr/bin/perl

# www.alrond.com
# Made by Alrond. 2007
# Check logfile. And if it more as 4 times, then drop IP in IPTABLES

use Mail::Mailer;

my $file401 = '/usr/nginx/logs/denied.log';
my $Tables = {};
my $counter = 0;
my $result = "";
my $textbody = "";

open (STAT,"$file401") || die;
@access=<STAT>;
close (STAT);

foreach $string(@access) {
    @item=split(/ /,$string);
	if ($item[2] ne '-') {
	    $Tables{$item[0]}++;
        }
}

for $IPadr (keys(%Tables))
{
    if ($Tables{$IPadr} > 4) {
    $counter=1;
    }
}

if ($counter){
    $result = `iptables-save | grep "A INPUT -s"`;    
    for $IPadr (keys(%Tables)) {
        if ($Tables{$IPadr} > 4) {
	    if ((index($result,$IPadr)) < 0){
	    system("iptables -I INPUT 1 -i eth0 -p tcp -m tcp -s $IPadr --dport 80 -j DROP");
	    $textbody = $textbody."\nBanned ".$IPadr." : ".$Tables{$IPadr}."\n\n";
	    $textbody = $textbody.`cat $file401 | grep $IPadr`."\n\n";    	    
	    }
	}
    }
}

# Change server name and email
if ($textbody ne ""){
    $mailer = Mail::Mailer->new('smtp', Server => 'your.server.here');
    $mailer->open({
	'From' => 'root',
        'To' => 'your@email.com',
	'Subject' => 'Banned IP'
    });
    print $mailer $textbody;
    $mailer->close();
}
