读取/var/log/secure,查找关键字 Failed,例如:
Sep 17 09:08:09 localhost sshd[29087]: Failed password for root from 13.7.3.6 port 44367 ssh2
Sep 17 09:08:20 localhost sshd[29087]: Failed password for root from 13.7.3.6 port 44367 ssh2
Sep 17 09:10:02 localhost sshd[29223]: Failed password for root from 13.7.3.6 port 56482 ssh2
Sep 17 09:10:14 localhost sshd[29223]: Failed password for root from 13.7.3.6 port 56482 ssh2
从这些行中提取IP地址,如果次数达到10次(脚本中判断次数字符长度是否大于1)则将该IP写到 /etc/hosts.deny
中。
步骤:
1、先把始终允许的IP填入 /etc/hosts.allow ,这很重要!比如:
sshd:19.16.18.1:allow
sshd:19.16.18.2:allow
2、脚本 /usr/local/bin/secure_ssh.sh
#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /usr/local/bin/black.list
for i in <code>cat /usr/local/bin/black.list</code>
do
IP=<code>echo $i |awk -F= '{print $1}'</code>
NUM=<code>echo $i|awk -F= '{print $2}'</code>
if [ ${#NUM} -gt 1 ]; then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
fi
done
3、将secure_ssh.sh脚本放入cron计划任务,每1分钟执行一次。
crontab -e
/1 * sh /usr/local/bin/secure_ssh.sh
原文:https://www.cnblogs.com/panblack/p/secure_ssh_auto_block.html