#!/bin/bash

#while true 
#do
#	OLD_MD5=$(md5sum /var/log/btmp|awk '{print $1}')
#	sleep 30
#	NEW_MD5=$(md5sum /var/log/btmp|awk '{print $1}')
#	sleep 2
#	if [ ! "${OLD_MD5}" == "${NEW_MD5}" ];then

		NUM=5
		DENY=/etc/hosts.deny
		LIST=/tmp/host_list.deny

		if [ ! -f $LIST ];then
		        touch $LIST
		fi

		lastb|sed '$d'|awk '/ssh:/{print $3}'|sort|uniq -c|while read SUM IP
		do      
		        
		        if [ $SUM -gt $NUM ];then
		                grep ${IP} ${DENY} &>/dev/null
		                rc=$?
		                if [ ! $rc -eq 0 ];then
		                echo "sshd:${IP}" >>${LIST}
		                fi
		        fi
		done

		TOTAL=$(wc -l $LIST|awk '{print $1}') 

		if [  -s ${LIST} ];then
			cat ${LIST} >>${DENY}
			echo -e "报警时间:$(date '+%F %H:%m:%S')\n远端地址列表:\n$(awk -F: '{print $2}' ${LIST})\n合计${TOTAL}个地址正在尝试通过SSH暴力破解入侵系统,尝试次数超过${NUM}次,已经阻止,并加入${DENY}黑名单中"|mail -s "SSH暴力破解报警" your_mail
		fi
		>$LIST
#	fi
#done
