温馨提示×

centos iptables如何限速

小樊
39
2026-09-05 19:54:22
栏目: 智能运维

在 CentOS 中使用 iptables 进行限速(流量控制),通常要结合 Linux Traffic Control(tc) 或直接使用 iptables 的 limit / hashlimit 模块。下面分几种常见场景说明。


一、使用 iptables + limit 模块(最简单,按包速率)

1️⃣ 限制入站每秒包数(如防止洪水攻击)

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

含义:

  • 每秒最多 1 个 ICMP 包
  • 突发允许 5 个
  • 超过直接 DROP

2️⃣ 限制某 IP 的新连接速率

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 10 -j DROP

含义:

  • 60 秒内同一 IP 最多 10 次 SSH 新连接

二、使用 hashlimit(推荐,按 IP 限速)

限制每个 IP 的 HTTP 请求速率

iptables -A INPUT -p tcp --dport 80 -m hashlimit \
--hashlimit-mode srcip \
--hashlimit-name http_limit \
--hashlimit-above 10/min \
--hashlimit-burst 5 \
-j DROP

含义:

  • 每个源 IP
  • 每分钟最多 10 个新连接
  • 超过丢弃

✅ 适合:

  • CC 攻击防护
  • 接口防刷

三、真正“带宽限速”(必须用 tc)

iptables 不能直接限制带宽(如 1Mbps),只能限制包/连接速率。

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

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

限制某 IP 上行带宽

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

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

四、CentOS 7+ 注意事项

  • CentOS 7 默认使用 firewalld
  • 若要用 iptables:
systemctl stop firewalld
systemctl disable firewalld
yum install iptables-services -y
systemctl enable iptables

五、总结建议

需求 推荐方案
防攻击 / 防刷 iptables + hashlimit
限制连接频率 iptables + limit
真正带宽限速 tc + iptables MARK
简单测试 tbf qdisc

如果你有 具体场景(如:限制某个 IP、某个端口、上行/下行),可以告诉我,我可以给你精准规则。

0