一个自动封暴力破解SSH的脚本

#!/bin/bash
# Name: banip.sh
# Author: Andowson Chang (andowson [at] gmail [dot] com)
# Version: 0.6
# Since: 2007-01-21
# Last Modified: 2013-06-09
 
# 修改這邊的參數
EXTERNAL_INTERFACE="eth0" # value can be "eth0" or "ppp0"
BANNED_HOSTS="/tmp/bannedhosts.txt"
BANNED_HOSTS_HISTORY="/tmp/history.txt"
IPTABLES="/sbin/iptables"
GREP_PARAM="^[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*"
export LANG=en_US
TODAY=`date +%Y-%m-%d`
RANGE=`date "+%b %e"`
SECURE_LOG="/tmp/secure.${TODAY}"
SUSPECTED="/tmp/failed.${TODAY}"
 
# 將資料資料範圍縮小到今天
grep "$RANGE" /var/log/secure > $SECURE_LOG
grep "Failed password for invalid user" $SECURE_LOG | awk '{print $13}' > $SUSPECTED
grep "Failed password" $SECURE_LOG | grep -v "invalid user" | awk '{print $11}' >> $SUSPECTED
 
# 找出攻擊的主機IP
cat $SUSPECTED | sort | uniq > /tmp/attacker_ip1
 
# 找出已被封鎖的主機IP
$IPTABLES -L OUTPUT -n | grep DROP | awk '{print $5}' | sort | uniq > /tmp/attacker_ip2
 
# 比對差異,找出新增的IP
comm -23 /tmp/attacker_ip[1-2] > $BANNED_HOSTS   # 新增主機資料
rm -rf /tmp/attacker*
 
# 將攻擊的主機IP加到iptables擋掉
for ip in $( grep $GREP_PARAM $BANNED_HOSTS )
do
    echo "Check $ip"
    #計算失敗次數
    failcount=`grep $ip $SUSPECTED | wc -l`
    #超過三次失敗者加入阻擋名單
    if [ $failcount > 5 ]; then
        echo "Deny access from host: $ip"
        $IPTABLES -A INPUT -i $EXTERNAL_INTERFACE -s $ip -j DROP
        $IPTABLES -A OUTPUT -o $EXTERNAL_INTERFACE -d $ip -j DROP
        # 將處理過的IP清單加到歷史檔去
        echo $ip >> $BANNED_HOSTS_HISTORY
    fi
done
 
rm -rf $BANNED_HOSTS
rm -rf $SECURE_LOG
rm -rf $SUSPECTED

crontab里新增一条

*/10 * * * * sh /root/test_ban_ssh.sh >/tmp/test_ban_ssh.log

还没有评论,快来抢沙发!

发表评论

  • 😉
  • 😐
  • 😡
  • 😈
  • 🙂
  • 😯
  • 🙁
  • 🙄
  • 😛
  • 😳
  • 😮
  • emoji-mrgree
  • 😆
  • 💡
  • 😀
  • 👿
  • 😥
  • 😎
  • ➡
  • 😕
  • ❓
  • ❗
  • 70 queries in 0.410 seconds