本篇出自:尼斐克的企鵝空間


#!/bin/bash
# Name: banip.sh
# Author: Andowson Chang (andowson [at] gmail [dot] com)
# Version: 0.1
# Last Modified: 2007-01-21

# 修改這邊的參數
EXTERNAL_INTERFACE="ppp0" # you must edit this
BANNEDHOSTFILE="/tmp/bannedhosts.txt" #edit this as required
HISTORYHOSTSFILE="/tmp/history.txt" #edit this as required
IPTABLES="/sbin/iptables"
GREP_PARAM="^[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*"

# 找出攻擊的主機IP
grep "Failed password for invalid user" /var/log/secure | cut -d" " -f13 | sort | uniq | cut -d":" -f4 > /tmp/attack.log
grep "Failed password for invalid user" /var/log/secure | cut -d" " -f14 | sort | uniq | cut -d":" -f4 >> /tmp/attack.log
# 刪除一些不是IP的字,目前發現的有from和port,也可以包含測試用的來源IP
sed -e '/from/d' -e '/port/d' -e '/192.168.1/d' /tmp/attack.log > /tmp/attack.txt

# 加入新增的主機
touch $HISTORYHOSTSFILE
sort /tmp/attack.txt | uniq > /tmp/ip1
sort $HISTORYHOSTSFILE | uniq > /tmp/ip2
comm -23 /tmp/ip[1-2] > $BANNEDHOSTFILE   # 新增站台資料
rm -rf /tmp/ip[1-2]
rm -rf /tmp/attack.*

# 將攻擊的主機IP加到iptables擋掉
for i in $( grep $GREP_PARAM $BANNEDHOSTFILE )
do
echo "Deny access to host: $i"
$IPTABLES -A INPUT -i $EXTERNAL_INTERFACE -s $i -j DROP
$IPTABLES -A OUTPUT -o $EXTERNAL_INTERFACE -d $i -j DROP
done

# 將處理過的IP清單加到歷史檔去
cat $BANNEDHOSTFILE >> $HISTORYHOSTSFILE
sort $HISTORYHOSTSFILE | uniq > /tmp/history.tmp
mv -f /tmp/history.tmp $HISTORYHOSTSFILE
rm -rf $BANNEDHOSTFILE


下面是我自己修改過的版本
Linux系統安全 - 阻擋ssh錯誤嘗試

EXTERNAL_INTERFACE="eth0" # you must edit this
BANNEDHOSTFILE="/tmp/bannedhosts.txt" #edit this as required
HISTORYHOSTSFILE="/tmp/history.txt" #edit this as required
IPTABLES="/sbin/iptables"
GREP_PARAM="^[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*\.[[:digit:]]*"
# 找出攻擊的主機IP
grep "Failed password for invalid user" /var/log/secure | cut -d" " -f13 | sort
| uniq | cut -d":" -f4 > /tmp/attack.log
grep "Failed password for invalid user" /var/log/secure | cut -d" " -f14 | sort
| uniq | cut -d":" -f4 >> /tmp/attack.log
# 刪除一些不是IP的字,目前發現的有from和port,也可以包含測試用的來源IP
sed -e '/from/d' -e '/port/d' -e '/192.168.1/d' /tmp/attack.log > /tmp/attack.tx
t

# 加入新增的主機
touch $HISTORYHOSTSFILE
sort /tmp/attack.txt | uniq > /tmp/ip1
sort $HISTORYHOSTSFILE | uniq > /tmp/ip2
comm -23 /tmp/ip[1-2] > $BANNEDHOSTFILE # 新增站台資料
rm -rf /tmp/ip[1-2]
rm -rf /tmp/attack.*

# 將攻擊的主機IP加到hosts.deny擋掉
for i in $( grep $GREP_PARAM $BANNEDHOSTFILE )
do
echo "Deny access to host: $i"
echo "sshd: $i" >> /etc/hosts.deny
done

# 將處理過的IP清單加到歷史檔去
cat $BANNEDHOSTFILE >> $HISTORYHOSTSFILE
sort $HISTORYHOSTSFILE | uniq > /tmp/history.tmp
mv -f /tmp/history.tmp $HISTORYHOSTSFILE
rm -rf $BANNEDHOSTFILE

arrow
arrow
    文章標籤
    Linux shell script ssh
    全站熱搜

    正義的胖虎 發表在 痞客邦 留言(1) 人氣()