centos7添加ip黑名单禁止某个ip访问
centos7用的是firewall 添加单个黑名单只需要把ip添加到 /etc/hosts.deny
格式 sshd:$IP:deny
vim /etc/hosts.deny
添加你要禁止的ip就可以了
sshd:192.168.1.147:deny
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qnpb1IFS-1620381132920)(https://www.pianshen.com/images/132/0a054294c58b0003aeca8bc080371d8c.png)]
这是允许的
/etc/hosts.allow
sshd:19.16.18.1:allow
sshd:19.16.18.2:allow
找了个,多次失败登录即封掉IP,防止暴力**的脚本 亲测有效 超过5次的就加到黑名单
1、编辑脚本
vim /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.txt
for i in `cat /usr/local/bin/black.txt`
do
IP=`echo $i |awk -F= '{print $1}'`
NUM=`echo $i|awk -F= '{print $2}'`
if [ $NUM -gt 5 ];then
grep $IP /etc/hosts.deny > /dev/null
if [ $? -gt 0 ];then
echo "sshd:$IP:deny" >> /etc/hosts.deny
fi
fi
done
2、创建记录登录失败次数的文件
touch /usr/local/bin/black.txt
3、添加定时 5分钟执行一次
vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/5 * * * * sh /usr/local/bin/secure_ssh.sh
启动定时任务
#加载任务,使之生效
crontab /etc/crontab
#查看任务
crontab -l
4、测试 ssh登录147 ssh 192.168.1.147
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7f5PmjKA-1620381132924)(https://www.pianshen.com/images/91/df3ddf37824fe353f4ca2aa85a58d553.png)]
5、查看黑名单列表是否记录
cat /usr/local/bin/black.txt
6、查看黑名单列表看是否添加进去了
cat /etc/hosts.deny
k.txt
[外链图片转存中...(img-kP1Tennc-1620381132931)]
6、查看黑名单列表看是否添加进去了
```shell
cat /etc/hosts.deny
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zAhXJPDh-1620381132939)(https://www.pianshen.com/images/691/0766dcbc762f1aac5485566fa739c3f3.png)]