894 views
Linux-shell脚本

拒绝恶意IP脚本(生产环境可用)

一键拒绝客户端IP恶意登录Linux服务器,发现客户端恶意登录服务器密码错误超过10次,则将客户端的IP加入到黑名单(2个小时自动解封原客户端IP)

Shell脚本实现服务器拒绝恶意IP登陆,编写思路如下:

1.登陆服务器日志/var/log/secure;

2.检查日志中认证失败的行并打印其IP地址;

3.将IP地址写入至防火墙;

4.禁止该IP访问服务器SSH 22端口;

5.将脚本加入Crontab实现自动禁止恶意IP;

[code]

#!/bin/bash

#Auto drop ssh failed IP address

#By ying 2017年9月20日16:58:28

#Define Path variables

SEC_FILE=/var/log/secure

IP_ADDR=`awk ‘{print $0}’ /var/log/secure|grep -i “fail”| egrep -o “([0-9]{1,3}\.){3}[0-9]{1,3}” | sort -nr | uniq -c |awk ‘$1>=3 {print $2}’`

DENY_CONF=/etc/hosts.deny

TM1=`date +%Y%m%d%H%M`

DENY_IP=”/tmp/2h_deny_ip.txt”

echo

cat <<EOF

++++++++++++++welcome to use ssh login drop failed ip+++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++————————————++++++++++++++++++

EOF

echo

for ((j=0;j<=5;j++)) ;do echo -n -e “\033[32m-\033[0m”;sleep 1;done

echo

for i in `echo $IP_ADDR`

do

    cat $DENY_CONF |grep $i >/dev/null 2>&1

    if [ $? -ne 0 ];then

        grep “$i” $DENY_IP>>/dev/null 2>&1

        if [ $? -eq 0 ];then

            TM3=`date +%Y%m%d%H%M`

            IP1=`awk -F”[#:]” ‘/’$i’/ {print $2,$4}’ $DENY_IP|awk ‘{if(‘$TM3’>=$2+2) print $1}’`

            if [ ! -z $IP1 ];then

                echo “sshd:$IP1:deny #$TM1” >>$DENY_CONF

                sed -i “/$IP1/d” $DENY_IP

            fi

        else

            echo “sshd:$i:deny #$TM1” >>$DENY_CONF

        fi

    fi

done

 

#Allow IP to access

TM2=`date +%Y%m%d%H%M`

IP2=`awk -F”[#:]” ‘/sshd/ {print $2,$4}’ $DENY_CONF|awk ‘{if(‘$TM2’>=$2+2) print $1}’`

for k in `echo $IP2`

do

    echo $k

    sed -i “/$k/d” $DENY_CONF

    echo “sshd:$k:deny #$TM2” >>$DENY_IP

done

[/code]

Leave a Reply

影子专属博客 赣ICP备17013143号