温馨提示×

ubuntu iptables如何限流量

小樊
47
2026-10-18 14:47:14
栏目: 智能运维

在 Ubuntu 上,可以使用 iptables 配合 流量控制(tc / htb) 或 iptables limit / quota 模块 来限制流量。下面按常见需求分类说明。


一、使用 iptables 限制【连接/包速率】(不是严格限带宽)

1. 限制每秒包数量(防攻击常用)

iptables -A INPUT -p tcp --dport 80 -m limit --limit 10/s --limit-burst 20 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j DROP

说明:

  • --limit 10/s:每秒最多 10 个包
  • --limit-burst 20:突发最多 20 个

⚠️ 这只是“速率限制”,不是带宽限制。


二、使用 iptables 限制【总流量(配额)】

2. 限制某个 IP 的总流量

iptables -A INPUT -s 192.168.1.100 -m quota --quota 104857600 -j ACCEPT
iptables -A INPUT -s 192.168.1.100 -j DROP

说明:

  • 100MB(104857600 字节)
  • 超过后规则失效,进入 DROP

查看剩余:

iptables -L -v -n

⚠️ 重启 iptables 后配额会清零。


三、真正“限制带宽”(推荐方式:iptables + tc)

iptables 本身不能直接限速带宽,需要配合 tc(Traffic Control)。

3. 限制某 IP 的上行/下行带宽(示例:限制 1Mbps)

(1)限制出口(服务器发出)

tc qdisc add dev eth0 root handle 1: htb
tc class add dev eth0 parent 1: classid 1:1 htb rate 1mbit

iptables -t mangle -A POSTROUTING -s 192.168.1.100 -j MARK --set-mark 10
tc filter add dev eth0 protocol ip parent 1:0 handle 10 fw flowid 1:1

(2)限制入口(常用 IFB 或 ingress)

modprobe ifb
ip link set ifb0 up

tc qdisc add dev eth0 ingress
tc filter add dev eth0 parent ffff: protocol ip u32 match ip src 192.168.1.100 flowid 1:1

四、更简单的方法(不只用 iptables)

✅ 推荐工具

  • wondershaper(最简单)
apt install wondershaper
wondershaper eth0 1024 512
  • 上行 1Mbps,下行 512Kbps

  • nftables(新系统推荐)

  • tc + htb(最专业)


五、总结建议

需求 推荐方式
防刷接口 iptables limit
限制总流量 iptables quota
限制带宽 tc + iptables MARK
快速限速 wondershaper

如果你能说明:

  • 限制 哪个 IP / 端口
  • 上行还是下行
  • 目标 带宽大小

我可以给你一条可直接用的完整命令。

0 踩