首页 » Linux » 20道shell第6题

20道shell第6题

 

企业实战题6:请用至少两种方法实现!
写一个脚本解决DOS攻击生产案例
提示:根据web日志或者或者网络连接数,监控当某个IP并发连接数或者短时内PV达到100,即调用防火墙命令封掉对应的IP,监控频率每隔3分钟。防火墙命令为:iptables -I INPUT -s 10.0.1.10 -j DROP。

 

答案:

[root@nfs_server scripts]# cat shell6.sh 
#!/bin/bash


function iptables(){
while read line
do 
ip=`echo $line|awk '{print $2}'`
count=`echo $line|awk 'print $1'`
ip_count=`iptables -L -n |grep $ip|wc -l`
if [ $count -gt 100 -a $ip_count -lt 1 ]
 then
 iptables -I INPUT -s $ip -j DROP
 echo "$line is dropped" >>/tmp/droplist.log
fi 

done</tmp/log

}

function main(){
while true
do 
`grep -v "^$" access_www.log |awk '{print $1}'|sort|uniq -c
`>/tmp/log
#netstat -an|grep EST|awk -F '[: ]+' '{print $6}'|sort|uniq -c >/tmp/log
iptables
sleep 180
done 
}
main

[root@nfs_server scripts]#

别人的答案:

[root@shell scripts]# vi dos.sh
#!/bin/bash
 
log=/tmp/tmp.log
 
[ -f $log ] || touch $log
 
function add_iptables(){
    whileread line
        do
          ip=`echo $line|awk '{print $2}'`
          count=`echo $line|awk '{print $1}'`
            if [ $count -gt 100 ] && [`iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
             then
                iptables -I INPUT -s $ip -jDROP
                echo "$line isdropped" >>/tmp/droplist.log
            fi
        done<$log
}
 
 
function main(){
    whiletrue
           do
             #awk '{print $1}' access.log|grep-v "^$"|sort|uniq -c >$log
             netstat -an|grep EST|awk -F '[:]+' '{print $6}'|sort|uniq -c >$log
             add_iptables
             sleep 180
    done
}
 
main

 

原文链接:20道shell第6题,转载请注明来源!

0