這個 Script 需要 iptables 配合,為了方便,我使用 iptables-save 把設定後的檔案留在/etc/iptables.conf
目前的問題在於:寫的太沒效率了。還有就是他會更動原本的auth.log檔(...Failed password XXX 改成 IP Deny from iptables ...XXX),所以如果有需要用,又想要保留原本auth.log檔的人請自行備份修改。
- 代碼: 選擇全部
#Usage: Deny ssh attacks by iptables
#Auth: snowmantw(at)gmail.com
#Version: 0.0
#License: You think this such poor shell script need a license?
# Anyway, if license is import for someone, this script is under GPL.
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH
cat /var/log/auth.log|grep -n "Failed password"|sed 's/^.*from//g'|sed 's/port.*$//g' > /tmp/badips.txt
#Get ips.
sort /tmp/badips.txt|uniq -dc > /etc/badips.txt
length=`wc /etc/badips.txt|awk '{print $1}'`
num=0
while [ "$num" != "$length" ]
do
num=$(($num+1))
is_bad=`nl /etc/badips.txt|sed 's/^\ \{5\}//g'|grep ^"$num"|awk '{print $2}'`
result=$(($is_bad>5))
if [ "$result" == 1 ]; then
badip=`nl /etc/badips.txt|sed 's/^\ \{5\}//g'|grep ^"$num"|awk '{print $3}'`
echo "Detected bad ip : $badip , times : $is_bad"
iptables -I INPUT -i all -s $badip -j DROP
echo "Iptables rejected it."
cat /var/log/auth.log |sed "s/^.*Failed\ password.*$/IP denied by iptables (use shell script) $badip /g" > /var/log/auth.log
fi
#Ignore tries < 5
done
iptables-save > /etc/iptables.conf
exit 0
寫完後想想,我的壞習慣就是在「應該」有別的工具好用情況下,還自己動手。
另外請問各位,有辦法查到對方連線時的MAC Address嗎?或者是我一定要從封包下手...(C++拿出來用的時候了?)