VPN技术 · 2023年11月10日 0

监控特定端口流量

监控特定端口流量

为了在不修改程序源代码的情况下监控特定端口的流量,可以使用Linux系统自带的Iptable工具。通过添加简单的规则,可以实现对端口流量的统计。然而,需要注意的是,服务器重启或Iptable服务重启时,统计数据会被清空。

添加需要监控的端口

1、输入流量监控

以下示例展示了如何监控目标端口8080的输入流量(-dport是目标端口的缩写)。

 iptables -A INPUT -p tcp --dport 8080

2、输出流量监控

以下示例显示了如何监控来源端口8080的输出流量(-sport是源端口的缩写)。

 iptables -A OUTPUT -p tcp --sport 8080

查看统计数据

iptables -L -v -n -x

示例结果:

8080端口接收的流量为2885字节,发送的流量为8240字节。

 Chain INPUT (policy ACCEPT 202 packets, 25187 bytes)   pkts   bytes target   prot opt in   out   source        destination    18   2885      tcp -- *   *    0.0.0.0/0      0.0.0.0/0      tcp dpt:8080  Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)   pkts   bytes target   prot opt in   out   source        destination  Chain OUTPUT (policy ACCEPT 184 packets, 45774 bytes)   pkts   bytes target   prot opt in   out   source        destination    12   8240      tcp -- *   *    0.0.0.0/0      0.0.0.0/0      tcp spt:8080 

重置统计数据

注意:此操作将重置所有端口的统计数据。

1、重置所有输入端口的统计数据。

iptables -Z INPUT

2、重置所有输出端口的统计数据。

iptables -Z OUTPUT

移除统计端口

1、移除输入端口的监控。

 iptables -D INPUT -p tcp --dport 8080

2、移除输出端口的监控。

 iptables -D OUTPUT -p tcp --sport 8080