温馨提示×

Debian iptables如何限制流量

小樊
46
2026-07-15 09:22:33
栏目: 智能运维

在 Debian 系统中,可以使用 iptables 结合 流量匹配模块来实现流量限制。常见需求包括:限制每秒包数(PPS)带宽速率连接数等。下面按常见场景给你一些实用示例。


一、限制每秒数据包数量(防洪水 / 限速)

1️⃣ 限制 ICMP(ping)流量(防 ping flood)

iptables -A INPUT -p icmp --icmp-type echo-request \
  -m limit --limit 1/second --limit-burst 5 \
  -j ACCEPT

iptables -A INPUT -p icmp -j DROP

含义:

  • 每秒最多 1 个 ping
  • 突发最多 5 个
  • 超过则丢弃

2️⃣ 限制 TCP 新建连接速率(防 SYN flood)

iptables -A INPUT -p tcp --syn \
  -m limit --limit 10/second --limit-burst 20 \
  -j ACCEPT

iptables -A INPUT -p tcp --syn -j DROP

二、限制某个 IP 的访问速率

限制某个 IP 每秒最多 5 个包

iptables -A INPUT -s 192.168.1.100 \
  -m limit --limit 5/second --limit-burst 10 \
  -j ACCEPT

iptables -A INPUT -s 192.168.1.100 -j DROP

三、限制端口流量(如 SSH)

限制 SSH(22)连接频率

iptables -A INPUT -p tcp --dport 22 \
  -m limit --limit 3/min --limit-burst 5 \
  -j ACCEPT

iptables -A INPUT -p tcp --dport 22 -j DROP

四、限制带宽(iptables 本身能力有限)

⚠️ iptables 不能直接限制带宽(如 1Mbps)
需要配合 tc(Traffic Control) 使用。

示例:限制出口带宽为 1Mbps(eth0)

tc qdisc add dev eth0 root tbf \
  rate 1mbit burst 32kbit latency 400ms

查看:

tc qdisc show dev eth0

删除:

tc qdisc del dev eth0 root

五、限制连接数(比流量更常用)

限制单个 IP 最多 10 个 SSH 连接

iptables -A INPUT -p tcp --dport 22 \
  -m connlimit --connlimit-above 10 \
  -j REJECT

六、保存 iptables 规则(Debian)

apt install iptables-persistent
netfilter-persistent save

否则重启后规则会丢失。


七、常用查看命令

iptables -L -n -v
iptables -L INPUT -v

八、总结对照表

需求 方法
限制包速率 -m limit
限制连接数 -m connlimit
限制带宽 tc
防攻击 iptables + limit
长期生效 iptables-persistent

如果你能说明 具体场景(如:限制某个 IP、限制下载速度、限制 Docker、限制某个端口),我可以给你更精确的配置方案。

0