防暴力破解密码的脚本

前几天,突然发现日志文件/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次。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章