使用iptables可精确统计特定端口的累计流量,通过添加INPUT和OUTPUT规则并查看其计数器实现;若需实时监控,则推荐iftop或nethogs;为确保规则重启后生效,需在Debian/Ubuntu上使用iptables-persistent,在RHEL/CentOS上保存至配置文件;此外,结合sar、vnstat、nethogs、tcpdump等工具可全面监控网络性能。

想在Linux上快速查看特定端口的流量统计?我的经验是,
iptables
iftop
nethogs
要统计特定端口的流量,我们通常会利用
iptables
具体来说,你可以为目标端口添加两条不影响实际转发的计数规则。比如,我们要统计8080端口的TCP流量:
添加计数规则: 为了不干扰现有防火墙策略,我们通常将这些规则添加到链的末尾,或者创建专门的计数链。但为了快速获取统计,直接追加到
INPUT
OUTPUT
DROP
REJECT
# 统计进入8080端口的TCP流量 sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT # 统计从8080端口发出的TCP流量 sudo iptables -A OUTPUT -p tcp --sport 8080 -j ACCEPT
这里我用了
-j ACCEPT
iptables
RETURN
查看统计结果: 执行以下命令,你会看到每条
iptables
pkts
bytes
sudo iptables -L -v -n
在输出中,找到你为8080端口添加的规则,就能看到它们的累计流量了。
清零计数器: 如果你想重新开始统计,或者只是想看某个时间段内的流量,可以清零所有规则的计数器:
sudo iptables -Z
或者,只清零特定规则的计数器(这需要知道规则的编号,或者使用更复杂的匹配):
# 假设你的规则是INPUT链的第X条,但通常直接Z掉所有更方便 # sudo iptables -Z INPUT X
实时流量监控: 如果你的需求是实时查看流量,而不是累计统计,那么
iptables
iftop
nethogs
iftop
# 安装(Debian/Ubuntu) sudo apt install iftop # 安装(CentOS/RHEL) sudo yum install epel-release && sudo yum install iftop # 监控eth0接口上8080端口的流量 sudo iftop -i eth0 -f 'port 8080'
它会显示类似
top
nethogs
# 安装(Debian/Ubuntu) sudo apt install nethogs # 安装(CentOS/RHEL) sudo yum install epel-release && sudo yum install nethogs # 监控eth0接口,并显示进程名 sudo nethogs -d 1 eth0 # 如果想过滤端口,可能需要结合其他工具,或者在nethogs输出后手动查找 # nethogs本身没有直接的端口过滤参数,但你可以用tcpdump捕获后分析,或者在nethogs输出中找
netstat
ss
我以前也经常犯这个错误,总觉得
netstat
ss
netstat
ss
iptables
iptables
iptables
不同的Linux发行版有不同的处理方式:
Debian/Ubuntu系列: 通常使用
iptables-persistent
sudo apt install iptables-persistent
安装过程中会询问你是否保存当前的IPv4和IPv6规则,选择“是”。
iptables
sudo netfilter-persistent save # 或者直接 sudo service netfilter-persistent save
这会将规则写入
/etc/iptables/rules.v4
/etc/iptables/rules.v6
iptables-persistent
systemctl status netfilter-persistent.service
RHEL/CentOS系列: 这些系统通常使用
iptables
firewalld
iptables
iptables
iptables
sudo service iptables save # 或者对于较新的系统 sudo iptables-save > /etc/sysconfig/iptables
这会将规则写入
/etc/sysconfig/iptables
iptables
sudo systemctl enable iptables sudo systemctl start iptables
注意: 如果你的系统默认使用
firewalld
iptables
firewalld
firewalld
iptables
firewalld
firewall-cmd
firewalld
我的建议是,如果你只是为了统计流量而添加
iptables
很多时候,我们不光要看某个端口忙不忙,更要看整个网络链路是不是健康。除了特定端口的流量,还有很多维度可以监控Linux系统的网络性能,这能帮助我们更全面地了解问题。
接口级别的整体流量:
sar -n DEV
sysstat
sar
eth0
sar -n DEV 1 5 # 每秒刷新一次,共5次
vnstat
sudo apt install vnstat # 或 yum install vnstat sudo vnstat -u -i eth0 # 初始化数据库 vnstat # 查看统计
collectd
Prometheus node_exporter
进程级别的网络使用:
lsof -i :port
strace
procfs
sudo lsof -i :8080
nethogs
更深层的包分析:
tcpdump
Wireshark
tshark
sudo tcpdump -i eth0 port 8080 -w /tmp/port8080.pcap # 捕获后可以用 Wireshark 打开 /tmp/port8080.pcap 分析
网络连通性和延迟:
ping
traceroute
mtr
mtr
ping
traceroute
综合来看,针对不同的监控需求,我们需要选择不同的工具。
iptables
iftop
nethogs
sar
vnstat
tcpdump
以上就是Linux怎么查看特定端口的流量统计的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号