Bann ip script when you have no firewall

darklord1

Well-Known Member
Jul 8, 2006
58
0
156
cPanel Access Level
Root Administrator
I'm no perl programmer by any means, I just got a server a few months ago and have learned a few nice little tidbits along the way.

A friend of mine recently told me that they had to bann ips through iptables, and iptables alone. I felt bad for this person and decided to do something about it.

So here it goes, My Bann script:

First create a file in /scripts/ name bann.

Code:
touch /scripts/bann
Then open it up in a text editor ( pico /scripts/bann ), put this inside it:

Code:
#!/usr/bin/perl



foreach( @ARGV )
{
my $ip = $_;
#Check the ip to make sure its valid, if not, do not try to enter that ip in the iptables.
if ($ip !~ /^([\d]+)\.([\d]+)\.([\d]+)\.([\d]+)$/){
print $ip." is not a valid ip to bann.\n";
} else{
print "Are you sure you want to bann " .$ip. "?(y/n)";   
chomp( my $q = <STDIN> );
    if ( $q =~ /^y/i ) {
my $bannem = 'iptables -I INPUT -s '. $ip .' -j DROP';
system($bannem);

print "This ip was Just banned: ";
print $ip;
print "\n";
}
}
}
Now open /etc/bashrc in a text editor ( pico etc/bashrc ),
And put this at the very end of the file:

Code:
alias bann="/scripts/bann";
Yeah I know Looks simple enough but hey this is the first real perl script Ive made, and making sure that a real ip is entered is important, I have never trusted input from any form so checks are always necessary.

Now I give you this because it does 2 things to make it easier on you, instead of making you type out: iptables -I INPUT -s <ip> -j DROP with every ip you want to bann, this shortens you up to: bann <ip>
Also, it makes use of Multiple ips. Basically, if you type bann ip1 ip2 ip3. It will bann all 3 ips with a single command.

This to me is a usefull script, ecspecially for a friend of mine, now I offer it to you, comments, feedback, sudjestions, all welcome.

Have fun with this.
 

DevilSun

Member
Apr 26, 2007
11
0
151
You can use the following command to check the connection of the IPs:


netstat -na |awk {'print $5'}|awk -F : {'print $1'}|grep -v STREAM|grep -v DGRAM|grep -v 127.0.0.1|grep -v ]|grep -v 0.0.0.0|sort|uniq -c|sort -nr


you can create simple script which will pars the results of this command and bann the IP address if the connection more the 50 (for example).
It's simple but usefull command ;)
 

brianoz

Well-Known Member
Mar 13, 2004
1,146
7
168
Melbourne, Australia
cPanel Access Level
Root Administrator
There's a standard tool for this called CSF - see the link in the post above. It does comprehensive security monitoring and firewall stuff and best of all, it's completely free. It's seen as the standard for cPanel servers these days.

It's about two lines of copy-and-paste to install and it comes standard with a WHM interface to make life easy...

www.configservers.com/cp/csf.html