shell补-特殊玩法-安全防护案例

发布时间 2023-12-15 10:55:19作者: WeChat2834
shell补-特殊玩法-安全防护案例
  1. 案例1:编写一个shell脚本解决类DDOS攻击的生成案例,请更加web日志或者系统网络连接数,监控当某个ip并非连接数,若短时间内PV达到100(阈值),即调用防火墙命令封掉对应的ip.
  2. 防火墙命令 iptables -I INPUT -s IP地址 -j drop
  3. 查看被封的ip:iptables -nL
  1. 风险每个ip地址的连接数量(ss -ant) netstat.log
  2. 结果ip 每个ip次数存放起来
  3. 过滤这个文件判断 ip出现的次数是否大于100 并且防火墙规则中没有屏蔽过ip
  4. 大于 iptables禁掉
  5. 读取下个
#################取出ip
##先准备类似的日志文件
[root@localhost ser]# for i in {1..7} ; do echo '10.112.11.81:9293'>> testip.log ; echo '10.112.85.884'>> testip.log ;done
[root@localhost ser]# while read line ; do  echo "vvscp $line" >>testnewlog ;done < testip.log 
[root@localhost ser]# while read line ; do  echo "tcp $line" >>testnewlog ;done < testip.log 
[root@localhost ser]# more testnewlog
tcp 10.112.11.85:9293
....
tcp 10.112.85.884
tcp 10.112.11.81:9293
tcp 10.112.85.884
tcp 10.112.11.81:9293
tcp 10.112.85.884
vvscp 10.112.11.85:9293
...
####'[ :.]+' 该部分将空格冒号点做为分隔符号,'/^tcp/{print $5}' 匹配tcp开头的去打印第五列
###sort排序
##uniq -c  应该是分组统计了
[root@localhost ser]# awk -F'[ :.]+' '/^tcp/{print $5}'  testnewlog |sort|uniq -c
     10 81
     10 85
     20 884
#####################################案例脚本开始
[root@localhost ser]# cat testip.sh 
#!/bin/bash
##############################################
# File Name:testip.sh
# Version:v1.0
# Author:mrxu
# Organization:https://www.cnblogs.com/xjianbing/
##############################################

filelog=~/tmp/ser/testnewlog
tmpfile=/root/tmp/ser/servertmp

awk -F '[ :.]+' '/^tcp/{print $5}' $filelog|sort|uniq -c|sort -rn > ${tmpfile}

while read line
    do
        ip=${line##* }
        count=${line% *}
    ###    echo "ip: $ip   访问次数 $count"  
    if [ $count -ge 100 -a `iptables -nL |grep -wc $ip` -eq 0] 
    	then
    	iptables -I INPUT -s ${ip} -j drop ####如果访问次数大于100,且没在已屏蔽的ip中则调用命令封禁。
    fi
    done< ${tmpfile}
[root@localhost ser]# ll
总用量 16
-rw-r--r--. 1 root root   34 11月 17 14:36 servertmp
-rw-r--r--. 1 root root  867 11月 17 14:09 testip.log
-rw-r--r--. 1 root root  489 11月 17 14:36 testip.sh
-rw-r--r--. 1 root root 1686 11月 17 14:09 testnewlog
[root@localhost ser]# cat servertmp 
     20 884
     10 85
     10 81
[root@localhost ser]# bash testip.sh 
ip: 884   访问次数 20
ip: 85   访问次数 10
ip: 81   访问次数 10
[root@localhost ser]#