如何利用 iptables 统计某个 ip 地址+端口号 的数据量

iptables用于linux的防火墙,可以设置允许/禁止网络连接,也可以用来做负载均衡(reroute)防止DDOS攻击等。

如果需要监控某一个ip地址在某一个端口的数据流量,也可以用到 iptables.

例如,我需要监控ip地址是 192.168.1.5 的机器和 本机端口 8080 和 8090 交换的网络数据流量,可以按照如下添加 rules (需要 root 执行,注意 sport 和 dport 参数别写错了):

#!/bin/bash
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -A OUTPUT -d 192.168.1.5 -p tcp -m tcp --sport 8080 -j ACCEPT
iptables -A INPUT -s 192.168.1.5 -p tcp -m tcp --dport 8080 -j ACCEPT
iptables -A OUTPUT -d 192.168.1.5 -p tcp -m tcp --sport 8090 -j ACCEPT
iptables -A INPUT -s 192.168.1.5 -p tcp -m tcp --dport 8090 -j ACCEPT

添加这些 rule 之前可以先清理当前的 iptables 规则:

sudo iptables -L  # 查看当前rules
sudo iptabels -F  # 清除当前rules

然后运行如下命令可以查看连接的流量:

localhost$ sudo iptables -nvxL
Chain INPUT (policy ACCEPT 109045 packets, 120330262 bytes)
    pkts      bytes target     prot opt in     out     source               destination
      49     3720 ACCEPT     tcp  --  *      *       192.168.1.5         0.0.0.0/0            tcp dpt:890
    1249    50026 ACCEPT     tcp  --  *      *       192.168.1.5         0.0.0.0/0            tcp dpt:8080
       0        0 ACCEPT     tcp  --  *      *       192.168.1.5         0.0.0.0/0            tcp dpt:8090

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
    pkts      bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 108503 packets, 120187996 bytes)
    pkts      bytes target     prot opt in     out     source               destination
      37   233199 ACCEPT     tcp  --  *      *       0.0.0.0/0            192.168.1.5         tcp spt:8090
     201  6270564 ACCEPT     tcp  --  *      *       0.0.0.0/0            192.168.1.5         tcp spt:8080
       0        0 ACCEPT     tcp  --  *      *       0.0.0.0/0            192.168.1.5         tcp spt:8090
       0        0 ACCEPT     tcp  --  *      *       0.0.0.0/0            192.168.1.5         tcp spt:8080

将流量统计信息清零:

localhost$ sudo iptabels -Z

需要实时监控,可以使用 watch 命令重复执行:

watch -n 0.5 iptables -nvxL

需要注意的一点就是,这里统计的数据包含了tcp/ip协议头的数据(以及其他协议头),所以跟程序中实际发送的数据量有点出入,不过应用程序发送的数据量一般比较大,协议头的数据量可以忽略不计。

see ref link:
https://www.booleanworld.com/depth-guide-iptables-linux-firewall/
https://www.thegeekstuff.com/2011/01/iptables-fundamentals/
https://serverfault.com/questions/195894/monitor-number-of-bytes-transferred-to-from-ip-address-on-port

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值