运维经验 Linux 自动屏蔽超标访问IP的 bash 脚本
发布: 2009-8-14 20:04 | 作者: phpsir | 查看: 31次
Linux 自动屏蔽超标访问IP的 bash 脚本
有Linux就是好使, 吃嘛嘛香
# author phpsir QQ 733905
maxnum=40
#最大单IP允许链接数
ipfile="/tmp/80link.txt"
ipopenfile="/root/openip.txt"
nsfile="/tmp/netstat80.txt"
myip=`/sbin/ifconfig eth0 | grep inet | awk '{print $2}' | sed 's/addr://' | grep .`
echo "start shell"
netstat -an | grep "$myip:80" > $nsfile
echo "Total Links = " `cat $nsfile | wc -l `
echo "Total Links ESTABLISHED = " `cat $nsfile | grep ESTABLISHED | wc -l `
echo "Total Links SYNC = " `cat $nsfile | grep SYN | wc -l `
cat $nsfile | awk '{print $5}' | awk -F: '{print $1}' | sort|uniq -c|sort -rn | head -n 10 > $ipfile
cat $ipfile | while read oneline
do
ip=`echo $oneline | cut -d " " -f 2`
num=`echo $oneline | cut -d " " -f 1`
str="$ip has linked $num "
if [ $num -gt "$maxnum" ]
then
/sbin/iptables -L -n | grep "$ip" >/dev/null
status=`echo $?`
if [ $status -eq 1 ]
then
echo "deny $ip ,because $str "
/sbin/iptables -A INPUT -p tcp -s $ip -d $myip --dport 80 -j REJECT
echo "BAN " $ip " OK "
#/sbin/iptables -L -n | grep "$ip"
else
echo > /dev/null
#echo "$str alread reject"
fi
else
echo > /dev/null
#echo "$str $ip ok ,less $maxnum "
fi
done
echo "ALLOW IP"
if [ -f $ipopenfile ]
then
for openip in `cat $ipopenfile`
do
echo "open $openip"
/sbin/iptables -D INPUT -p tcp -s $openip -d $myip --dport 80 -j REJECT > /dev/null 2>&1
done
fi
date
echo "end shell"
有Linux就是好使, 吃嘛嘛香
# author phpsir QQ 733905
maxnum=40
#最大单IP允许链接数
ipfile="/tmp/80link.txt"
ipopenfile="/root/openip.txt"
nsfile="/tmp/netstat80.txt"
myip=`/sbin/ifconfig eth0 | grep inet | awk '{print $2}' | sed 's/addr://' | grep .`
echo "start shell"
netstat -an | grep "$myip:80" > $nsfile
echo "Total Links = " `cat $nsfile | wc -l `
echo "Total Links ESTABLISHED = " `cat $nsfile | grep ESTABLISHED | wc -l `
echo "Total Links SYNC = " `cat $nsfile | grep SYN | wc -l `
cat $nsfile | awk '{print $5}' | awk -F: '{print $1}' | sort|uniq -c|sort -rn | head -n 10 > $ipfile
cat $ipfile | while read oneline
do
ip=`echo $oneline | cut -d " " -f 2`
num=`echo $oneline | cut -d " " -f 1`
str="$ip has linked $num "
if [ $num -gt "$maxnum" ]
then
/sbin/iptables -L -n | grep "$ip" >/dev/null
status=`echo $?`
if [ $status -eq 1 ]
then
echo "deny $ip ,because $str "
/sbin/iptables -A INPUT -p tcp -s $ip -d $myip --dport 80 -j REJECT
echo "BAN " $ip " OK "
#/sbin/iptables -L -n | grep "$ip"
else
echo > /dev/null
#echo "$str alread reject"
fi
else
echo > /dev/null
#echo "$str $ip ok ,less $maxnum "
fi
done
echo "ALLOW IP"
if [ -f $ipopenfile ]
then
for openip in `cat $ipopenfile`
do
echo "open $openip"
/sbin/iptables -D INPUT -p tcp -s $openip -d $myip --dport 80 -j REJECT > /dev/null 2>&1
done
fi
date
echo "end shell"

