function display_iplist()
{
   clear
   netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
}

function block_ips()
{
   clear
   netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n > badips.txt
   if [ -f badips.txt ]
     then
       echo "! ! ! All Ips having connections greater than the number specified will be blocked on the server ! ! !"
       echo -n "Enter the number -- >"
       read Max
       echo ""
       declare -a ARRAY
       let "index=0"
       for BAD_IP in `cat badips.txt`
           do
             ARRAY[$index]=$BAD_IP
             let "index+=1"
           done
           for ((i=0; i<$index; i++))
              do
                rem=`expr $i % 2`
                if [ $rem = 0 ]
                   then
                      if [ "${ARRAY[$i]}" -ge $Max ]
                        then
                           if [ ${ARRAY[$i+1]} != 0.0.0.0 ]
                             then
                                 echo ""${ARRAY[$i+1]}" has "${ARRAY[$i]}" active connections"
                                 echo "Executing \"iptables -A INPUT -s "${ARRAY[$i+1]}" -j DROP"\"
                                 iptables -A INPUT -s "${ARRAY[$i+1]}" -j DROP
                                 if [ $? -eq 0 ] #Checking that whether IP blocked successfully or not
                                    then
                                        echo "${ARRAY[$i+1]} has been blocked on the server"
                                        echo "`date | awk '{ print $1,$3",",$2,$6 }'` iptables -A INPUT -s "${ARRAY[$i+1]}" -j DROP" >> blockips.log
                                    else
                                        echo "Unable to block ${ARRAY[$i+1]} on the server"
                                        echo "`date | awk '{ print $1,$3",",$2,$6 }'` Unable to Block Ip ${ARRAY[$i+1]} by executing \"iptables -A INPUT -s "${ARRAY[$i+1]}" -j DROP"\" >> blockips.log
                                 fi
			    echo ""
                            fi
                      else
                          let "i+=1"
                      fi
                  fi
               done
else
                echo "Error: Cant read badips.txt"
fi

}

while :
do

  #  clear
    echo "-------------------------------------"
    echo " Main Menu "
    echo "-------------------------------------"
    echo "[1] Display list of Ips"
    echo "[2] Specify Max hits number"
    echo "[3] Exit/Stop"
    echo "====================================="
    echo -n "Enter your menu choice [1-3]: "

        read choice

        case $choice in

        1) display_iplist ;;
        2) block_ips ;;
        3) exit 0 ;;
        *) echo "Ossps...Please select choice 1,2 or 3" ;
           echo -n "Press a key " ; read ;;

        esac
done

