nginx屏蔽某一时间段访问量过大的IP

#!/bin/bash
# 1. 核心配置
LOG_DIR="/www/wwwlogs/"       # 日志目录
LOG_PATTERN="*.log"           # 日志文件匹配模式
# 切记白名单"/data/wwwroot/ip_whitelist.conf"放在屏蔽规则文件前面
DENY_FILE="/data/wwwroot/deny_ip.conf"  # 屏蔽规则文件
# 不屏蔽搜索引擎
SPIDER_UA="Baidu|Google|Sogou|Bing|360|Youdao|Shenma|Yisou"
THRESHOLD=1500                # 阈值(10分钟内请求次数)

# 2. 获取时间范围
current_time=$(date +"%d/%b/%Y:%H:")
ten_min_ago=$(date -d "10 minutes ago" +"%d/%b/%Y:%H:")
time_pattern="$current_time"
if [ "$current_time" != "$ten_min_ago" ]; then
    time_pattern="($current_time|$ten_min_ago)"
fi

# 3. 清空旧规则
sed -i '/^deny/d' "$DENY_FILE"

# 4. 处理日志文件
find "$LOG_DIR" -maxdepth 1 -type f -name "$LOG_PATTERN" | while read -r log_file; do
    if [ -f "$log_file" ] && [ -r "$log_file" ]; then
        echo "处理日志:$log_file"
        awk -v pattern="$time_pattern" -v spider="$SPIDER_UA" \
            '$4 ~ pattern && $9 == 200 && $12 !~ spider {print $1}' "$log_file"
    fi
done | sort | uniq -c | sort -nr \
| awk -v threshold="$THRESHOLD" '$1 >= threshold {print "deny " $2 "; # 总请求次数:" $1}' >> "$DENY_FILE"

# 5. 重新加载Nginx
nginx -s reload

# 输出统计
total=$(grep -c '^deny' "$DENY_FILE")
echo "完成,共添加 $total 条规则"

默认分类 2025-09-12 12:56:20 通过 网页 浏览(17)

共有0条评论!

发表评论

更换一道题!
放大的图片