SSH安全防护脚本–自动添加到/etc/hosts.deny

1 修改ssh默认端口

1
2
3
4
5
vim /etc/ssh/sshd_config
Port 2***


systemctl restart sshd

2 检查命令

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

3 编写脚本

vim limit_ssh.sh

# 输入密码错误10次以上,IP自动加入黑名单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#! /bin/bash
#chkconfig:2345 80 90
#decription:limit_ssh autostart
awk '/Failed/{print $(NF-3)}' /var/log/secure|sort|uniq -c|awk '{print $2 "=" $1}'  > /root/limit_ssh.txt
DEFINE="10"
for i in `cat  /root/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

4 添加脚本执行权限和开机启动

1
2
3
4
5
chmod +x limit_ssh.sh
ln -s /root/limit_ssh.sh /etc/rc.d/init.d/limit_ssh
chkconfig --add limit_ssh
chkconfig  limit_ssh on
chkconfig --list

5 添加定时检查任务

1
2
crontab -e
*/5 * * * * /bin/sh /etc/rc.d/init.d/limit_ssh >/dev/null 2>&1

6 其他

1
2
3
4
5
6
7
8
9
10
11
12
#设置白名单
echo "sshd:119.139..:allow" >>/etc/hosts.allow

#此规则为允许119.139..段的IP访问SSH服务。

#添加多条:
echo "sshd:192.168.0.,10.0.0.1,10.0.1.:allow" >>/etc/hosts.allow

# ip段:sshd:192.168..:allow  或者 sshd:192.168.0.*:allow

#禁止所有ip连接
 echo "sshd:all:deny" >> /etc/hosts.deny

tangbin0505


原创文章 198获赞 11访问量 7万+

关注
私信

展开阅读全文