自动封禁多次ssh fail的IP

查看ssh失败的IP和对应的次数

1
cat /var/log/secure |awk '/Failed/{print$(NF-3)}'|sort|uniq -c

脚本secure_ssh.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ vim /etc/shell/secure_ssh.sh
#!/bin/bash
awk '/Failed/{print $(NF-3)}' /var/log/secure|sort|uniq -c|awk '{print $2 "=" $1}' > /etc/shell/limit_ssh.txt
DEFINE="6"
for i in `cat /etc/shell/limit_ssh.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:deny" >> /etc/hosts.deny
fi
fi
done

赋权并写加入定时任务

1
2
3
chmod +x /etc/shell/secure_ssh.sh
$ crontab -e
*/5 * * * * /etc/shell/secure_ssh.sh > /dev/null 2>&1

本文来源于网络,有所改动

课程中心

Qianj.51CTO