• 服务器防止SSH暴力破解


    最近不知为啥,很多国外IP开始SSH暴力攻击服务器
    几次自己的测试服务器都被攻破了,改了ssh端口也没用,继续被暴力破解,应该是有脚本在批量破解就在想怎么防护,运维同事曾大神推荐了个faild2ban,使用起来感觉麻烦,于是网上搜索了个脚本改改,效果居然还挺好的。
    脚本内容如下:
    文件名secure_ssh.sh ,我存放在/opt目录下面(centos系统)

    #! /bin/bash
    cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /usr/local/bin/black.txt
    for i in `cat  /usr/local/bin/black.txt`
    do
      IP=`echo $i |awk -F= '{print $1}'`
      NUM=`echo $i|awk -F= '{print $2}'`
       if [ $NUM -gt 5 ];then
          grep $IP /etc/hosts.deny > /dev/null
        if [ $? -gt 0 ];then
          echo "sshd:$IP:deny" >> /etc/hosts.deny
        fi
      fi
    done
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    原理是 根据 /var/log/secure 文件,捞取密码失败五次以上IP信息 ,然后写入到/etc/hosts.deny,禁止相关ip ssh访问服务器,加入服务器没有secure 文件,则可以使用lastb 命令(用于查看失败登录ip信息

    效果如下

    [root@VM-16-10-centos opt]# lastb -n 10
             ssh:notty    82.157.47.238    Thu Aug 25 00:28 - 00:28  (00:00)
             ssh:notty    64.62.197.137    Wed Aug 24 21:07 - 21:07  (00:00)
    pi       ssh:notty    99.199.192.24    Wed Aug 24 18:52 - 18:52  (00:00)
    pi       ssh:notty    99.199.192.24    Wed Aug 24 18:52 - 18:52  (00:00)
    pi       ssh:notty    99.199.192.24    Wed Aug 24 18:52 - 18:52  (00:00)
    pi       ssh:notty    99.199.192.24    Wed Aug 24 18:52 - 18:52  (00:00)
    read     ssh:notty    92.255.85.70     Wed Aug 24 16:26 - 16:26  (00:00)
    read     ssh:notty    92.255.85.70     Wed Aug 24 16:26 - 16:26  (00:00)
    pi       ssh:notty    110.19.208.233   Wed Aug 24 14:43 - 14:43  (00:00)
    pi       ssh:notty    110.19.208.233   Wed Aug 24 14:43 - 14:43  (00:00)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    awk 命令 检索 信息
    sort|uniq -c 排序。并汇总出现次数,并将找到的ip输出到black.txt 并遍历black文件再和/etc/hosts.deny文件比较
    处理完脚本,再给加到定时任务里面
    先查看下定时任务

    crontab -l
    
    • 1

    然后编辑

    crontab -e
    
    • 1

    在出现的定时任务编辑加上下面语句,每隔一分钟(linux定时任务表达式从分钟起)执行一下脚本,汇总下攻击IP,并加入黑名单

    */1 * * * * sh  /opt/secure_ssh.sh
    
    • 1

    然后按 esc 输入wq!命令保存
    如果担心自己密码输入错误次数多,就把自己的 ip 加入的 hosts.allow里面

  • 相关阅读:
    Django笔记十八之save函数的继承操作和指定字段更新等实例方法
    2023 年最新 Docker 容器技术基础详细教程(更新中)
    MATLAB实现的图像分割之边缘检测和连接
    Layui + Flask | 实现数据表格修改(案例篇)(09)
    CompletableFuture异步优化代码
    DM-VERITY流程分析
    mysql8.0 保护登录信息
    MyBatis主要的类层次结构(Mybatis工具类)
    全国职业技能大赛云计算--高职组赛题卷②(容器云)
    【机器学习基础】决策树(Decision Tree)
  • 原文地址:https://blog.csdn.net/u011515165/article/details/126517186