You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell中检测日志中IP出现超X次并执行操作

日志IP频次触发操作解决方案

1. 筛选出现次数超过阈值的IP

可以通过以下命令直接提取日志中出现次数超过指定阈值的IP:

# 输出出现次数超过5次的IP
awk '{print $1}' access.log | sort | uniq -c | awk '$1 > 5 {print $2}'

如果想提升效率(减少管道操作),用awk一次性完成统计和筛选:

# 定义阈值为5,输出符合条件的IP
awk -v threshold=5 '{count[$1]++} END {for (ip in count) if (count[ip] > threshold) print ip}' access.log

2. 对符合条件的IP执行特定操作

通过while循环读取筛选出的IP,逐个执行自定义操作(比如封禁IP、导出专属日志等):

# 设置触发阈值
THRESHOLD=5

# 遍历IP并执行操作
awk -v threshold="$THRESHOLD" '{count[$1]++} END {for (ip in count) if (count[ip] > threshold) print ip}' access.log | while read -r IP; do
    # 示例1:打印处理提示
    echo "处理IP: $IP,出现次数超过${THRESHOLD}次"
    
    # 示例2:导出该IP的所有日志到单独文件
    grep "^${IP} " access.log > "${IP}_access_logs.txt"
    
    # 示例3:用iptables封禁该IP(需root权限)
    # iptables -A INPUT -s "${IP}" -j DROP
done

说明

  • 将代码中的THRESHOLD值替换为你实际需要的触发次数(如10、20)
  • 循环内的操作可根据需求自由修改,比如调用告警脚本、发送通知邮件等

内容的提问来源于stack exchange,提问作者CrazyRabbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:35:25