获取暴力破解密码的来源IP地址,并自动添加firewalld规则
file='/var/log/secure';
logfile='./securelog.txt';
current=`date +%Y-%m-%d_%H:%M:%S`;
echo "当前时间是:" $current "begin..." >> $logfile;
var=`date | cut -c 5-11`;
row_number=`cat /var/log/secure| grep "$var"| grep "Failed password"| wc -l`
if [ $row_number -lt 10 ];then
echo "$row_number次破解,暂不处理" >> $logfile;
elif [ $row_number -ge 10 ];then
echo "not secure" >> $logfile;
num=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u| wc -l`
if [ $num -eq 0 ];then
echo "very secure!">>$logfile;
elif [ $num -eq 1 ];then
repeat=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| wc -l`
if [ $repeat -gt 10 ];then
ipcount=`cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u`
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address=$ipcount reject"
if [ $? -eq 0 ]; then
echo "only one ip;add firewall rule succeed! $ipcount">>$logfile;
else
echo "only one ip;add firewall rule failed! $ipcount">>$logfile;
fi
fi
elif [ $num -gt 1 ];then
echo "more then one ip;" >> $logfile;
for ip in `cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'| sort -u`
do
if [ `cat $file | grep "Failed password"|egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'|grep $ip|wc -l` -gt 10 ];then
firewall-cmd --add-rich-rule="rule family='ipv4' source address=$ip reject"
if [ $? -eq 0 ]; then
echo "more then one ip;add firewall rule succeed! $ip">>$logfile;
else
echo "more then one ip;add firewall rule failed! $ip">>$logfile;
fi
fi
done
else
echo "something error!!!" >> $logfile;
fi
fi