一个专业运
维技术分享!

Centos下防止ssh暴力破解脚本

一. 问题的发现

今早上班继续干活时,发现云盘服务器SSH连接服务器发现异常的提示,仔细看了一下吓一小跳,被人尝试连接1333+,慌~~~

速度查一下log

[root@lab ~]# cd /var/log
[root@lab log]# ll -h

-rw-------. 1 root root 224K 7月 19 03:22 secure-20200719
-rw-------. 1 root root 0 7月 19 03:45 spooler
-rw-------. 1 root root 0 7月 18 21:13 spooler-20200719

打开日志文件瞧瞧

发现被无数不同的IP地址和不同的用户进行SSH尝试连接。

随便拿个IP地址,百度一下,全是国外的IP地址,太可恶了:

二. 防范办法

虽然我的密码很复杂了,但是为了以防万一,还是速度百度一下,斩草除根

注:修改之前,记得请把对应端口在防火墙添加规则。

1,修改SSH端口为 2298(这个端口建议使用 1024 以上的)

[[root@lab ~]# vim /etc/ssh/sshd_config
---------------配置如下----------------
Port 2298

2,重启SSH

[root@lab ~]# systemctl restart sshd

3.,查看端口是否更改

[root@lab ~]# netstat -ntlp | grep 2298
tcp    0   0 0.0.0.0:2298   0.0.0.0:*   LISTEN   15156/sshd          
tcp6   0   0 :::2298        :::*        LISTEN   15156/sshd

注:还有个步骤就是“禁止root登录”,我这里就不禁止root登录了,因为密码太复杂记不住,切换root用户不方便。

2. 防止 SSH 暴力破解脚本

注:同一个IP地址超过10次的尝试,就加入/etc/hosts.deny。

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

添加计划任务:

[root@lab ~]# crontab -e
*/5 * * * * /bin/bash /sshPrevent/ssh_pervent.sh
# 每五分钟检查一次

# 重启crontab
[root@lab ~]# systemctl restart crond

五分钟后,查看是否成功:

[root@lab ~]# cat /sshPrevent/black.txt 
103.101.232.208=1
103.108.187.4=2
103.248.220.249=15
104.131.93.33=1
104.236.122.193=2
104.236.186.24=2
104.236.246.16=1
104.244.79.33=4
104.248.211.180=2
......
------------------------------我是分割线-----------------------------
[root@zwlbsweb ~]# cat /etc/hosts.deny
#
# hosts.deny    This file contains access rules which are used to
#        deny connections to network services that either use
#        the tcp_wrappers library or that have been
#        started through a tcp_wrappers-enabled xinetd.
#
#        The rules in this file can also be set up in
#        /etc/hosts.allow with a 'deny' option instead.
#
#        See 'man 5 hosts_options' and 'man 5 hosts_access'
#        for information on rule syntax.
#        See 'man tcpd' for information on tcp_wrappers
#
sshd:103.248.220.249
sshd:104.248.88.106
sshd:106.12.18.37
sshd:106.51.230.186
sshd:106.75.17.91
sshd:112.21.188.183
sshd:112.221.179.133
......

小小的防范措施就到此完成了!

三. 隔一段时间查看效果如何

半天已经过去了,我们再次查看 secure 日志文件。



微信扫描下方的二维码阅读本文

赞(5) 打赏
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。小柳实验室 » Centos下防止ssh暴力破解脚本

相关推荐

  • 暂无文章

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏