Centos下防止ssh暴力破解脚本

2016年6月24日16:20:33 1 7,765
#! /bin/bash

cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /root/black.txt    #筛选出状态为Failed的ip和次数

cat /var/log/secure|awk '/Invalid user/{print $NF}'|sort|uniq -c|awk '{print $2"="$1;}' >> /root/black.txt   #筛选出状态为Invalid user的ip和次数

DEFINE="20"    #规定允许次数为20次

for i in `cat /root/black.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" >> /etc/hosts.deny
           fi
     fi
done

规定当登录失败或者非法用户的ip次数达到20次后就把ip加入到hosts.deny中。

因为secure日志文件是每周六就会自动存档,于是我们可以写个排程定制去跑这个脚本

每天凌晨1点运行

0 1 * * * /usr/local/bin/ssh_black.sh 2>&1 >>/dev/null
weinxin
聂扬帆博客
一个分享IT运维相关工作经验和实战技巧的个人博客

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:1   其中:访客  1   博主  0

    • avatar themebetter 0

      留个脚印,欢迎来themebetter问答讨论交流各种网站技术问题哦!