ssh 登录失败次数超过 3 次的 ip 直接加入 hosts.deny 文件

一、前言:

看日志发现许多系统登录失败的记录,就明白我可能是被黑客盯上了,本文就给大家分享一个防暴力破解的脚本,希望对大家有所帮助

注意:该教程,是基于swoole的毫秒定时器,因此必须有以下几个条件:

1、php > 7.1

2、安装了swoole 扩展。

二、具体步骤

1、编写脚本,将 ssh 登录失败次数超过 3 次的 ip 直接加入 hosts.deny 文件

/data/sciprt/denyHost.sh

#!/bin/bash
#Denyhosts SHELL SCRIPT
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"=" $1;}' >/root/denyHost.txt
DEFINE="3"
for i in `cat /root/denyHost.txt`
do
 IP=`echo $i|awk -F= '{print $1}'`
 NUM=`echo $i|awk -F= '{print $2}'`
 if [ $NUM -gt $DEFINE ]
 then
 ipExists=`grep $IP /etc/hosts.deny |grep -v grep |wc -l`
 if [ $ipExists -lt 1 ]
 then
 echo "sshd:$IP" >> /etc/hosts.deny
 fi
 fi
done

2、创建脚本执行文件 /data/script/denyHost.php

<?php
declare(strict_types = 1);
class DenyHost
{
 public function index()
 {
 $shell = 'sh /data/script/denyHost.sh';
 shell_exec($shell);
 }
}
swoole_timer_tick(500, function ($timerId) {
 (new DenyHost())->index();
});

3、添加记录文件

cd ~
touch denyHost.txt

4、给予sh脚本权限

cd /data/script
chmod 777 denyHost.sh

5、运行php脚本

cd /data/script
php denyHost.php

目前是可以随时ctrl c 打断这个脚本执行的,我们可以在后台运行这个php脚本

nohup php /data/script/denyHost.php &
6、如果要结束这个php脚本在后台运行

# 找到这个php脚本的pid
ps -a | grep php
# 返回结果
381 pts/0 00:00:00 php
kill -9 381

说明:这里使用的是swoole的毫秒定时器,较之 linux 自带的 crontab 定时任务,好处在于,swoole 的毫秒定时器最小单位可以是毫秒,而 crontab 最小单位是每分钟,实现防暴力破解并不理想。

7、验证效果

cat -n /etc/hosts.deny
扫码领红包

微信赞赏支付宝扫码领红包

发表回复

后才能评论