• shell 拒绝恶意连接脚本 centos7.x拒绝恶意连接脚本


    1. crontab -l 脚本频率:

        */2 * * * * /bin/bash /home/shell/deny.sh

    2. 脚本:

    1. rm -rf /home/shell/ip_list
    2. cat /var/log/secure | grep "Failed password for" | awk '{print$(NF-3)}' | sort | uniq -c > /home/shell/ip_list
    3. #cat /var/log/secure | grep "Invalid user" | awk '{print$(NF-2)}' | sort | uniq -c > /home/shell/ip_list
    4. # cat /var/log/secure | grep "Received disconnect from " | awk '{print$(NF-4)}' | awk -F: '{print$1}' | sort | uniq -c >> /home/shell/ip_list
    5. DEFINE=20
    6. cat /home/shell/ip_list | while read line
    7. do
    8. IP=`echo $line | awk '{print$2}'`
    9. NUM=`echo $line | awk '{print$1}'`
    10. if [ $NUM -gt $DEFINE ]; then
    11. grep $IP /etc/hosts.deny > /dev/null 2>&1
    12. if [ $? -gt 0 ]; then
    13. echo "sshd:$IP:deny # ="`date +%s` >> /etc/hosts.deny
    14. fi
    15. fi
    16. done
    17. #封禁段时间的IP进行解封,如果解封时间小于日志文件生成周期,会出现重复封禁、解封情况。特别是有的系统不会按指定时间重新生成secure日志文件。暂未解决重复封禁IP问题
    18. rm -rf /home/shell/list /home/shell/list1 #删除临时文件,如果有的话
    19. TIMES=`date +%s` #记录当前系统时间,用于跟已经封禁的IP进行对比
    20. cat /etc/hosts.deny | grep "sshd" > /home/shell/list #检查/etc/hosts.deny文件中是否有已经封禁的IP,如果有,则写入/home/shell/list文件,以供后面筛选
    21. if [ $? -eq 0 ] #如果上一条命令执行成功(即有被封禁IP),则执行后面的操作
    22. then
    23. cat /etc/hosts.deny | awk -F'=' '{print$2}' | sed '/^$/d' > /home/shell/list1 #将所有已经封禁的IP信息进行过滤,过滤出时间信息,写入/home/shell/list1文件
    24. cat /home/shell/list1 | while read line #通过while循环,依次读取时间信息
    25. do
    26. DATES=$[ TIMES-line ] #将当前时间跟IP封禁时间进行运算
    27. if [ $DATES -ge 604800 ] #如果封禁IP时间大于指定时间(这里是7天转换后的秒数),则继续执行后面的操作
    28. then
    29. lines=` head -n 1 /home/shell/list ` #将符合解封时间的信息写入变量,方便后面删除
    30. # sed -i '/'"$line"'/d' /home/shell/list1 #删除时间信息临时文件,这条可要可不要,因为前面是通过while 循环依次读取,不会重复读取第一行
    31. sed -i '/'"$lines"'/d' /etc/hosts.deny /home/shell/list #删除符合解封的IP记录。
    32. fi
    33. done
    34. else
    35. echo '没有需要解封的IP'
    36. exit 0
    37. fi

     3. 使用时,注意编码问题,最好先在服务器建好脚本文件,然后粘贴进去

    4.放入cron run即可

  • 相关阅读:
    【python】学会这八个自动化脚本,摸鱼的借口那不就来啦~
    AttributeError: type object ‘Image‘ has no attribute ‘fromarray‘
    [Golang]多返回值函数、defer关键字、内置函数、变参函数、类成员函数、匿名函数
    AD7021C 触摸感应加灯光调节芯片IC 可用于触摸台灯、触摸玩具灯等
    Unity 利用Cache实现边下边玩
    pytorch 中遇到的问题
    探索Java中最常用的框架:Spring、Spring MVC、Spring Boot、MyBatis和Netty
    八股文第七天
    智慧公厕擦手纸洗手液余量实时在线统计
    python经典小游戏:24速算(案例)
  • 原文地址:https://blog.csdn.net/qq_33919114/article/details/134407738