防止恶意扫描ssh登陆

脚本1:

#!/bin/bash #统计尝试登陆次数
cat /var/log/secure | grep “Failed password” | awk ‘{ print $(NF-3)}’ | sort -n | uniq -c | awk ‘{ print $2″=”$1}’ > abc.txt
#得到扫描失败的ip地址
ipaddr=($(cat /var/log/secure | grep “Failed password” | awk ‘{ print $(NF-3)}’ | sort -n | uniq -c | awk ‘{ print $2″=”$1}’))
for i in ${ipaddr[@]} ; do
        NUM=$(cat abc.txt | awk ‘{print $1}’)
        IP=$(cat abc.txt | awk ‘{print $2}’)
        if [[ $NUM > 15 ]]; #得到扫描超过15次的ip地址
        then
                grep $IP /etc/hosts.deny > /dev/null
                if [[ $? != 0 ]]; #判断该ip是否在/etc/hosts.deny中
                then
                        echo “sshd:$IP” >> /etc/hosts.deny
                fi
        fi

done

另一种写法:

#/bin/bash
##deny ssh from invalid remote client 
grep “Failed password”  /var/log/secure | awk ‘{ print $(NF-3)}’ | sort -n | uniq -c > /tmp/ssh_log


while read num ip
do
    if (($num > 15))
    then
        grep $ip /var/log/secure &>/dev/null
            if [[ $? != 0 ]]
            then
                echo “sshd:$ip” >> /etc/host.deny
            fi
    fi
done < /tmp/ssh_log

查询哪个ip扫描比较多的

cat /var/log/secure* | grep “Failed password” | awk ‘{ print $(NF-3)}’ | sort -n | uniq -c

grep “Failed password” /var/log/secure* | awk ‘{ print $(NF-3)}’ | sort -n | uniq -c

转载于:https://my.oschina.net/fengjihu/blog/192464

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注