一、前言:
使用 lastb 命令,可以查看当前系统登录失败的记录日志,如果很多,那就说明你可能被黑客盯上了。
注意:该教程,是基于swoole的毫秒定时器,因此必须有以下几个条件:
- php > 7.1
- 安装了swoole 扩展。 Linux 源码编译安装 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/hoshts.deny
转载来源: 老迟笔记