您的位置:首页 > 其它

iptables防攻击自动黑白名单脚本

2011-12-28 09:51 295 查看
在网上也看到过iptables黑白名单的脚本,拿下来都不符合,现在写了个自动黑白名单的脚本,已经在线上跑的了,有兴趣的朋友可以拿去试下。

脚本是相对简单的

1、因为crontab任务是按分来执行任务的,所以写一个每秒都执行任务的脚本,脚本如下,脚本名为“ipt.sh”

#!/bin/bash

SLEEPTIME=5

CONN=150

iptables_drop()

{

netstat -an| grep :80 | grep -v 127.0.0.1 |grep ESTABLISHED |awk '{ print $5 }' | sort|awk -F: '{print $1,$4}' | uniq -c | awk '$1>150 {print $1,$2}' > /root/black.txt

[ -z /root/black.txt ] && exit 0

for i in `awk '{print $2}' /root/black.txt`

do

for lm in `grep "\<$i\>" /root/black.txt | awk '{print $1}'`

do

two=`grep "\<$i\>" /root/bak.txt`

if [ "$i" != "$two" ]; then

[ $lm -gt $CONN ] && grep "\<$i\>" /root/work.txt > /dev/null

if [ $? -ne 0 ]; then

echo $i >> /root/bak.txt;

/sbin/iptables -I INPUT -p tcp -s $i --dport 80 -j DROP;

echo "/sbin/iptables -D INPUT -p tcp -s $i --dport 80 -j DROP" | at `date -d '+20 minutes' +%H:%M` && \

echo "sed -i \"/\<$i\>/d\" /root/bak.txt" | at `date -d '+20 minutes' +%H:%M`

fi

fi

done

sleep 1

done

}

while true; do

iptables_drop

sleep $SLEEPTIME

done

详细:具体操作方法在/home/script下建立ipt.sh脚本,在/root目录下建个work.txt文件,里面写着白名单ip,这样这个白名单ip访问量再大也不会被X掉了,一般正常的访问量,单1秒的时间里同一个ip 过来的连接不会有超过150个的,所以判断1秒时间里web的连接数超过150个,直接用iptables拉黑,然后再用at任务在一定时间里将其还原,我这里设置为20分钟,基本上就是这样了......如那位朋友还有好的方案,可以拿出来一起分享,技术因为分享而快乐,呵呵
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iptables 自动 黑白