前幾天,突然發現日誌文件/var/log/auth.log(ubuntu)或者/var/log/secure(centos),存在好多嘗試破解用戶密碼的現象,如下腳本通過獲取到日誌文件的IP地址,加入到/etc/hosts.deny文件中,拒絕該IP地址的嘗試登陸服務器。
#1.定義變量,獲取日誌中刷選的IP地址
DIR_file=/var/log/auth.log
IP_list=`awk '/Failed/{print $(NF-3)}' $DIR_file|sort|uniq -c|sort -nr|sed 's/ /,/g'|sed -e 's/^,*//g'`
#2.導出當前hosts.deny文件中的IP地址,導入到hosts.deny.ip中
grep -v "^#\|^$" /etc/hosts.deny|awk -F "sshd:" '{print $2}'|sort -nr|uniq -u >/etc/hosts.deny.ip
#3.將IP地址追加到/etc/hosts.deny.ip文件中
for i in $IP_list
do
conn=`echo $i|awk -F, '{print $1}'`
ip=`echo $i|awk -F, '{print $2}'`
if test $conn -gt 20;then
echo $ip >>/etc/hosts.deny.ip
#else
# echo $conn"小於20,不滿足基本條件"
fi
done
#4.去除/etc/hosts.deny.ip文件中重複的IP地址,生成/etc/hosts.deny.bak文件
cat /etc/hosts.deny.ip|sort -nr|uniq -u|awk '{print "sshd:"$1}'>/etc/hosts.deny.bak
#5.去除/etc/hosts.deny.bak文件重複的值,導入到/etc/hosts.deny中,生成新的列表
grep -v "^#\|^$" /etc/hosts.deny.bak|uniq -u >/etc/hosts.deny
\rm -rf /etc/hosts.deny.ip
\mv /etc/hosts.deny.bak /tmp/hosts.deny.bak
可以使用此腳本來拒絕網絡中的IP多次嘗試暴力破解,腳本中的條件可以根據實際情況來設定,目前默認的是20次。