跳转至

从服务器上用ngrep抓取真实客户端的访问

从服务器上抓取来自真实客户端的访问,ngrep 部署在服务器上

ngrep 可以理解成"带正则匹配的 tcpdump",原理很简单:

1. 底层用 libpcap 抓包 和 tcpdump、tshark 一样,ngrep 通过 libpcap 把网卡设为混杂模式,从内核里拿到原始数据包的副本。它只是旁路"复制"一份数据来看,不会影响真实流量。

2. 先用 BPF 过滤器做第一层筛选 命令末尾的 tcp port 8000 是 BPF 表达式。它在内核态就执行了,只把匹配的包交给用户态,效率高。这一层只看 IP、端口、协议等包头信息。

3. 再对 payload 做正则匹配 包到了用户态后,ngrep 剥掉以太网、IP、TCP 头,取出 TCP 载荷(也就是 HTTP 报文文本),然后用正则(或加 -X 用十六进制)去匹配你给的字符串,比如 X-Real-IP: 172.17.192.1。匹配上才打印,没匹配上就丢弃。

整个流程就是:

网卡 → 内核 → libpcap (BPF过滤) → ngrep (对每个包的payload做正则) → 输出

对网卡8000端口检查来自192.1.0.0/16,192.2.0.0/16 的请求

yum install -y ngrep
# 日志目录
mkdir -p /var/log/ngrep

# 启动脚本
cat > /usr/local/bin/ngrep-monitor.sh <<'EOF'
#!/bin/bash
exec ngrep -d eth0 -l -q -t -W byline '(X-Real-IP|X-Forwarded-For): 192\.[12]\.[0-9]+\.[0-9]+' tcp port 8000 >>
/var/log/ngrep/ngrep.log 2>&1
EOF
chmod +x /usr/local/bin/ngrep-monitor.sh

# systemd 服务
cat > /etc/systemd/system/ngrep-monitor.service <<'EOF'
[Unit]
Description=ngrep monitor for X-Real-IP 192.1/192.2 on port 8000
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/ngrep-monitor.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# 日志轮转(保留14天,压缩)
cat > /etc/logrotate.d/ngrep <<'EOF'
/var/log/ngrep/ngrep.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
EOF

# 启动并设置开机自启
systemctl daemon-reload
systemctl enable --now ngrep-monitor

查看日志
tail -0f /var/log/ngrep/ngrep.log