grep $IP /etc/hosts.deny > /dev/null
    if [ $? -gt 0 ];then
      echo "sshd:$IP:deny" >> /etc/hosts.deny
    fi
  fi
done
#echo “* * * * * sh /etc/secure_ssh.sh” >> /etc/crontab
#chmod -x /etc/secure_ssh.sh
#crontab /etc/crontab
**测试**  
 ![在这里插入图片描述]()  
 ![在这里插入图片描述]()  
 创建脚本  
 ![在这里插入图片描述]()  
 故意输错密码,然后输入正确的密码,可以登录。  
 ![在这里插入图片描述]()  
 ![在这里插入图片描述]()


## ubuntu方式
mkdir /script
touch /script/checkBlackIp.sh
 chmod 755 /script/checkBlackIp.sh /scriptchown root:root /script/checkBlackIp.sh
vim /script/checkBlackIp.sh
 #!/bin/sh
 lastb |awk ‘/ssh/{print $3}’ |sort |uniq -c |awk ‘{print $2"="$1}’ >/script/black.listfor i in cat /script/black.list do
 IP=echo $i |awk -F= '{print $1}' NUM=echo $i |awk -F= '{print $2}' if [ ${#NUM} -ne 1 ]; then
 grep $IP /etc/hosts.deny >/dev/null
 if [ ! IP:deny" >>/etc/hosts.deny
echo "$IP \c"
    fi
fi
done
echo “is denied now.”
手工运行测试
 sudo bash checkBlackIp.shecho > /var/log/wtmp;echo > /var/log/btmp;history -c;
lastb |awk ‘/ssh/{print $3}’ |sort |uniq -c |awk ‘{print $2"="$1}’
http://www.ctohome.com/FuWuQi/36/650.html  
 ![在这里插入图片描述]()


定时2分钟执行1次

#crontab -e
*/2 * * * * root sh /script/checkBlackIp.sh

![在这里插入图片描述]()


![在这里插入图片描述]()  
 如果被拒绝登陆了,需要在vi /etc/hosts.deny里面将拒绝ip删除,就可以登录 了;注释之后,就不会再添加进/etc/hosts.deny  
 ![在这里插入图片描述]()  
 ![在这里插入图片描述]()  
 已经被拒绝登陆  
 ![在这里插入图片描述]()  
 **如何清空拦截记录**  
 1、清空/删除history记录

echo > /var/log/wtmp;echo > /var/log/btmp;history -c;

2、清空wtmp
echo > /var/log/wtmp # 此文件默认打开时乱码的,里面可以看到ip等等信息

#last

3、删除 /etc/hosts.deny里面被拒绝的IP地址

#vi /etc/hosts.deny

![在这里插入图片描述]()
**扩展**  
 crontab -e配置完成后,如何把保存并退出?


**1.Ctrl+O 写入**


2.出现“FIile name to Write…”,输入Enter


**3.Ctrl+x 保存输出**


提示“crontab:installing new crontab”表示成功。


**(root权限下)**
crontab启动:/etc/init.d/cron start ( service cron start )
crontab重启: /etc/init.d/cron restart (service cron restart )
crontab关闭: /etc/init.d/cron stop ( service cron stop )
在终端中,可以利用 ps -aux|grep cron查询crontab状态,默认情况下,是自启动的。


(系统级的)做系统级配置我们会直接配置 /etc/crontab


(用户级的)一般还是建议大家使用 crontab -e ,这样系统也会帮着检查我们配置的脚本语法。


注意,Ubuntu和CentOS的SSH日志文件路径不一样:



> 
> /var/log/auth.log Ubuntu是这个文件  
>  /var/log/secure CentOS是这个文件


![img]()
![img]()
![img]()