|
通过 iptables 限制连接数量的另一种方法
作者:bixjun
首先建立目录:
mkdir /tmp/blockip
mkdir /tmp/blockip/ip
mkdir /tmp/blockip/mac
然后建立一个 shell 脚本程序(内容如下),运行即可。可以限制内网机器的连接数量,超出连接数量即被阻断,待连接数降回设定值之后即可自动恢复连接。可用于限制内网中个别机器的多线程连接。
#!/bin/bash
rm -f /tmp/blockip/ip/*
rm -f /tmp/blockip/mac/*
while true
do
touch 2>/dev/null `netstat-nat -n |awk '{print $2;}'| \
grep 192.168 | \
awk ' FS=":" { print $1}'| \
sort | \
awk ' BEGIN {
COUNT=0
IP=""
}
{
if ( $1 != IP ) {
if (COUNT >= 200) {
print "/tmp/blockip/ip/"IP
}
COUNT=0
IP=$1
} else {
COUNT++
}
}'`
cd /tmp/blockip/ip
for ip in *
do
if [ -e $ip ] && [ ! -e ../mac/$ip ]
then
touch 2>/dev/null ../mac/$ip
iptables -I FORWARD -s $ip -j DROP
iptables -I FORWARD -d $ip -j DROP
echo `date "+%Y-%m-%d %H: %M: %S "`$ip was blocked for `netstat-nat -n -s $ip|wc|awk '{print $1}'` connections
fi
done
cd /tmp/blockip/mac
for ip in *
do
if [ -e $ip ]
then
netstat-nat -n -s $ip | wc | \
awk -v IP=$ip ' {
if ( $1 < 100 ) {
print "iptables -D FORWARD -s " IP " -j DROP"
print "iptables -D FORWARD -d " IP " -j DROP"
print "rm " IP
print "rm ../ip/" IP
print "echo `date \"+%Y-%m-%d %H: %M: %S \"`\"" IP " was unblocked\""
}
} ' >> unblock
fi
done
if [ -e unblock ]
then
chmod 700 unblock
./unblock
rm unblock -f
fi
sleep 6
done |
|