你可以下以下的指令先將目前iptables的rule給儲存在/etc/iptables.rule底下
接下來讓rule可以在server網卡啟動的時候生效sudo sh -c "iptables-save -c > /etc/iptables.rule"
在/etc/network/interfaces加入下面這行指令
pre-up iptables-restore < /etc/iptables.rule接下來就可以利用script來幫忙自動block ip了
我參考了國外的網站稍微改了一些地方讓這個script可以用在ubuntu server上
#!/bin/bash
#Collecting list of ip addresses connected to port 80
netstat -plan|grep :80|awk {'print $5'}|cut -d: -f 1|sort|uniq -c|sort -nk 1 > /root/iplist
#Limit the no of connections
LIMIT=100;
for ip in `cat /root/iplist |awk '{print $2}'`;do
if [ `grep $ip /root/iplist | awk '{print $1}'` -gt $LIMIT ]
then
echo "100 connection from $ip... `grep $ip /root/iplist | awk '{print $1}'` number of connections... Blocking $ip";
#Blocking the ip ...
/sbin/iptables-save > /etc/iptables.rule;
CHECK_IF_LOCALIP=0;
/sbin/ifconfig | grep $ip > /dev/null;
if [ $? -ne $CHECK_IF_LOCALIP ]
then
{
FLAG=0;
grep $ip /etc/iptables.rule | grep DROP > /dev/null;
if [ $? -ne $FLAG ]
then
iptables -I INPUT -s $ip -j DROP;
else
echo " Ipaddress $ip is already blocked ";
fi
}
else
echo " Sorry, the ip $ip cannot be blocked since this is a local ip of the server ";
fi
fi
done
這個script是會偵測netstat看同一個ip的連線是否超過100個,如果有超過100個就會加入block的ip列表中,你可以修改LIMIT的參數來決定你要限制多少個連線就把IP給block掉。script存檔後要給他可執行的權限
chmod +x /root/ipblock.sh然後加入crotab才會執行, 你可以修改/etc/crontab,加入下面這行
*/1 * * * * root /root/ipblock.sh因為我把script放在root的目錄下,並且將檔案存檔為ipblock.sh,實際情況請參考自己的設定,這樣就會每分鐘就去檢查一次netstat的狀況,看看是否有超過限制的連線
如果你的系統是redhat的就可以使用下面這個script
#!/bin/bash
#Collecting list of ip addresses connected to port 80
netstat -plan|grep :80|awk {'print $5'}|cut -d: -f 1|sort|uniq -c|sort -nk 1 > /root/iplist
#Limit the no of connections
LIMIT=100;
for ip in `cat /root/iplist |awk '{print $2}'`;do
if [ `grep $ip /root/iplist | awk '{print $1}'` -gt $LIMIT ]
then
echo "100 connection from $ip... `grep $ip /root/iplist | awk '{print $1}'` number of connections... Blocking $ip";
#Blocking the ip ...
/etc/rc.d/init.d/iptables save > /dev/null;
CHECK_IF_LOCALIP=0;
/sbin/ifconfig | grep $ip > /dev/null;
if [ $? -ne $CHECK_IF_LOCALIP ]
then
{
FLAG=0;
grep $ip /etc/sysconfig/iptables | grep DROP > /dev/null;
if [ $? -ne $FLAG ]
then
iptables -I INPUT -s $ip -j DROP;
else
echo " Ipaddress $ip is already blocked ";
fi
}
else
echo " Sorry, the ip $ip cannot be blocked since this is a local ip of the server ";
fi
fi
done
差別就是在iptables一些用法還有路徑的不同參考來源:
沒有留言 :
張貼留言