核心是检测异常流量后自动启动tcpdump抓包,按阈值触发、带时间戳保存、用临时文件锁防重启,并通过systemd服务实现常驻运行与日志追溯。

在 Linux 中编写脚本自动处理异常抓包,核心是「检测异常流量 + 自动启动抓包 + 按条件停止 + 保存带时间戳的文件」。不依赖人工值守,关键在于定义清楚什么是“异常”,再用轻量工具组合实现闭环。
明确“异常”的判断依据
没有统一标准,需根据实际场景选择 1–2 种可脚本化的指标:
-
端口突增连接数:如
ss -tn state established | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -1发现某 IP 连接数超 100 -
特定协议/端口流量激增:用
iftop -P 80 -t -s 1或tcpreplay配合tcpdump -c 1快速采样比对 -
已知恶意特征触发:如
tcpdump -i eth0 -c 1 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and tcp[tcpflags] & (tcp-syn|tcp-fin) == (tcp-syn|tcp-fin)'抓到 TCP SYN+FIN(非常规扫描) -
系统日志关键词:
journalctl -n 10 --no-pager | grep -q "kernel:.*Dropped.*SYN"等丢包或防攻击日志
用 shell 脚本串联检测与抓包
以下是一个最小可用示例(保存为 auto-capture.sh),每 5 秒检测一次,发现连接数异常即启动抓包 60 秒后自动保存:
#!/bin/bash
INTERFACE="eth0"
THRESHOLD=80
DURATION=60
PCAP_DIR="/var/log/captures"
mkdir -p "$PCAP_DIR"
while true; do
COUNT=$(ss -tn state established | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -1 | awk '{print $1}')
if [[ "$COUNT" -gt "$THRESHOLD" ]] && [[ ! -f "/tmp/capture_active" ]]; then
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
touch /tmp/capture_active
tcpdump -i "$INTERFACE" -w "$PCAP_DIR/abnormal_${TIMESTAMP}.pcap" -G "$DURATION" -W 1 &
echo "Started capture at $TIMESTAMP due to $COUNT connections"
sleep "$DURATION"
rm -f /tmp/capture_active
fi
sleep 5
done
注意:-G 和 -W 组合确保超时自动轮转,避免无限写入;用临时文件锁防止重复启动。
进阶:用 systemd service 后台常驻 + 日志记录
把脚本变成服务更可靠:
- 创建
/etc/systemd/system/auto-capture.service:
[Unit] Description=Auto TCPDump on Anomaly After=network.target [Service] Type=simple User=root ExecStart=/usr/local/bin/auto-capture.sh Restart=always RestartSec=10 StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target
- 启用:
sudo systemctl daemon-reload && sudo systemctl enable --now auto-capture - 查看状态:
sudo journalctl -u auto-capture -f
这样即使终端断开、机器重启,抓包逻辑仍持续运行,并有完整日志追溯。
后续分析建议(非必须但实用)
自动生成的 pcap 文件可配合简单命令快速筛查:
- 看 top talker:
tshark -r abnormal_20240510_142201.pcap -T fields -e ip.src -e ip.dst | sort | uniq -c | sort -nr | head -5 - 过滤疑似扫描行为:
tshark -r file.pcap 'tcp.flags.syn == 1 and tcp.flags.ack == 0' -T fields -e ip.src -e tcp.dstport | sort | uniq -c - 导出 HTTP 请求路径:
tshark -r file.pcap -Y "http.request" -T fields -e http.host -e http.request.uri
不复杂但容易忽略:所有自动抓包都应限制磁盘空间,建议加 cron 清理旧文件,例如每天删 7 天前的 pcap。











