首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Linux网络数据包跟踪脚本

Linux网络数据包跟踪脚本

作者头像
YaoQi
发布2025-07-14 18:54:43
发布2025-07-14 18:54:43
7400
代码可运行
举报
运行总次数:0
代码可运行

iptable的策略中,有一个用来记录日志用的'-j LOG',可以在匹配的数据包经过此策略时记一条日志,可以帮我们弄清数据包在netfilter链表中的处理过程,定位出问题的位置。

其支持的参数有:

代码语言:javascript
代码运行次数:0
运行
复制
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29 letters long, and useful for distinguishing messages in the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.

为了方便,我写了个脚本,在各表的默认链的开始结尾处各添加一个日志记录点:

代码语言:javascript
代码运行次数:0
运行
复制
#! /bin/bash
# netfilter_debug.sh  
ACTION=$1
FILTER=$2
if [ "$#" -ne 2 -a "$1" != "I" -a "$1" != "D" ];then
        echo "USAGE: $0 <ACTION> <FILTER>"
        echo "EG: $0 I '-s 1.1.1.1'"
        exit 1
fi

LOG_LEVEL=7
OPTIONS="--log-level $LOG_LEVEL -m comment --comment debuglog --log-ip-options"

## tables and chains
TABLES="raw mangle nat filter"

raw_chains="PREROUTING OUTPUT"
mangle_chains="PREROUTING INPUT FORWARD OUTPUT POSTROUTING"
nat_chains="PREROUTING INPUT OUTPUT POSTROUTING"
filter_chains="INPUT FORWARD OUTPUT"

for table in $TABLES; do
        table_chains="${table}_chains"
        eval "chains=\$$table_chains"

        for chain in $chains; do
                echo "$chain" "$table"
                if [ "$ACTION" = "I" ]; then
                        iptables -t $table -I $chain $FILTER -j LOG --log-prefix "$chain $table:I " $OPTIONS 
                        iptables -t $table -A $chain $FILTER -j LOG --log-prefix "$chain $table:O " $OPTIONS
                elif [ "$ACTION" = "D" ]; then
                        iptables -t $table -D $chain $FILTER -j LOG --log-prefix "$chain $table:I " $OPTIONS
                        iptables -t $table -D $chain $FILTER -j LOG --log-prefix "$chain $table:O " $OPTIONS
                fi

        done
  
done

echo "Run:tail -f /var/log/messages  or dmesg -w"
代码语言:javascript
代码运行次数:0
运行
复制
用起来也很简单:

netfilter_debug.sh  I/D '-d 1.1.1.1'

代码语言:javascript
代码运行次数:0
运行
复制
添加就用I (insert),删除就用D (delete),后边用单引号包起来的是匹配策略。

可以用iptables-save查看添加进去的策略:

此时ping一下目标IP:ping 1.1.1.1 -c 1

用 tail -f /var/log/messages 或 dmesg -w 看下日志结果:

很清晰的就看到此数据包从OUTPUT处理过程中穿过了各个表,又在POSTROUTING过程中穿过两个表。

如果你有自定义或感兴趣的链,可以加入到各表的列表中。

补充下处理过程的概念关系:

1. 属于某个的,各个表中的链相互独立,比如mangle表和filter表都有OUTPUT链,他们是相互独立的。

2. 数据经过5个处理过程时,会依次穿过特定的表,默认查找其中链名和当前处理过程名相同的链进行处理。

我之前就是把处理过程当成链(因为他们名字相同),以为是链穿过表了,有和我一样的小伙伴吗😀

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-11-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 漫跑的小兔 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档