最近發現服務器流量有些異常,通過日志查看到有一些IP大量訪問服務器,於是找到了這個腳本來過濾此類IP,具體規則為,如果在10000個請求中,有1000個請求來自於同一個IP,那麼這個IP即可判定為攻擊IP。
在服務器上新創建一個腳本文件:
vi block_ips.sh
放入以下內容:
#!/bin/bash logfiles=( /tmp/logs/rainbow_access.log /tmp/logs/eric_access.log ) whitelist=$(last | awk '{print $3}' | grep ^[1-9] | sort | uniq | xargs) function check_root(){ if [ $EUID -ne 0 ]; then echo "This script must be run as root" exit 1 fi } function block_ips(){ blacklist=$@ if [ ! -z "${blacklist}" ]; then for ip in ${blacklist} do if ! $(echo ${whitelist} | grep -wq ${ip}); then if ! $(/sbin/iptables-save | grep -wq ${ip}); then echo "Blocked ${ip}" /sbin/iptables -I INPUT -s ${ip}/32 -p tcp -m tcp --dport 80 -j DROP fi fi done fi } function check_post(){ page=$1 tailnum=$2 retry=$3 command="grep -w POST ${logfile} |tail -n ${tailnum} |grep -w ${page} |awk '{print \$1}' |sort |uniq -c |awk '(\$1 > ${retry}){print \$2}'" blacklist=$(eval ${command}) block_ips ${blacklist} } function check_all(){ tailnum=$1 retry=$2 command="tail -n ${tailnum} ${logfile} |awk '{print \$1}' |sort |uniq -c |awk '(\$1 > ${retry}){print \$2}'" blacklist=$(eval ${command}) block_ips ${blacklist} } check_root for logfile in ${logfiles[@]} do check_post wp-login.php 10000 100 check_post wp-comments-post.php 10000 100 check_all 10000 1000 done
為該文件賦予可編輯權限:
chmod +x block_ips.sh
添加自動任務,沒5分鐘執行一次:
vi /etc/crontab
加入以下內容:
*/5 * * * * /home/rainbow/sbin/block_attack_ips.sh 00 01 * * * /etc/init.d/iptables restart
即可。