恶意访问
更新: 2025/8/7 字数: 0 字 时长: 0 分钟
提示
不知道为什么在 nginx 里面老看有外国 ip 访问,然后看 nginx 感觉资源访问都不太对就自动封了这些
sh
# 首先创建文件
sudo mkdir -p /data/myoa/tool/block
# 然后直接一下子写入
sudo tee /data/myoa/tool/auto_block.sh > /dev/null << 'EOF'
#!/bin/bash
# ==================== 配置区 ====================
# 日志文件路径(你可以改成实际的 Nginx/Apache/自定义日志)
LOG_FILE="/data/myoa/nginx/logs/access.log"
# 已封禁 IP 记录文件,避免重复封禁
BLACKLIST_FILE="/data/myoa/nginx/logs/blocked_ips.txt"
# 需要匹配的“恶意”关键字或正则(可自行添加)
# 这里举例包括:请求 .env、探测 RDP、Hello-World UA、zgrab 扫描
PATTERNS=('\.env' 'Hello-World' '\x00' 'zgrab' '/webui/' 'mstshash' '/metadatauploader')
# =================================================
# 如果日志文件不存在,则退出
if [ ! -f "$LOG_FILE" ]; then
echo "[`date '+%Y-%m-%d %H:%M:%S'`] ERROR: 日志文件 $LOG_FILE 不存在,退出" >> /var/log/auto_block_error.log
exit 1
fi
# 确保黑名单记录文件存在
touch "$BLACKLIST_FILE"
chmod 600 "$BLACKLIST_FILE"
# 读取日志中匹配上述任意关键字的 IP(可按时间戳切分)
grepped_ips=$(grep -iE "$(IFS='|'; echo "${PATTERNS[*]}")" "$LOG_FILE" \
| awk '{print $1}' \
| sort -u)
# 遍历每个可疑 IP,若不在 BLACKLIST_FILE 中,则添加到防火墙并记录
for ip in $grepped_ips; do
# 跳过空行
[ -z "$ip" ] && continue
# 如果 IP 格式不合法就跳过
if ! [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
continue
fi
# 检查是否已在黑名单文件中
if grep -Fxq "$ip" "$BLACKLIST_FILE"; then
continue
fi
# 封禁该 IP(示例用 iptables;如果用 firewalld 可改成 firewall-cmd)
/usr/sbin/iptables -I INPUT -s "$ip" -j DROP 2>> /var/log/auto_block_error.log
# 记录到黑名单文件
echo "$ip" >> "$BLACKLIST_FILE"
echo "[`date '+%Y-%m-%d %H:%M:%S'`] Blocked $ip" >> "${BLACKLIST_FILE}.log"
done
exit 0
EOF
sh
# 给权限
sudo chmod +x /data/myoa/tool/auto_block.sh
# 加定时器自动运行
sudo tee /etc/cron.d/auto_block > /dev/null << 'EOF'
# 每 5 分钟执行一次自动封禁脚本
*/5 * * * * root /data/myoa/tool/auto_block.sh
EOF
# 重启下定时器
sudo systemctl restart crond