温馨提示×

centos iptables怎么限速

小樊
42
2026-09-02 16:09:10
栏目: 智能运维

在 CentOS 上使用 iptables 进行限速,通常是通过 limit 模块(限制包速率)或结合 tc(traffic control) 做更精确的带宽限速。下面按常见场景说明。


一、使用 iptables limit 模块(按包/连接限速)

1. 限制特定端口的 NEW 连接速率(防爆破)

例如限制 SSH(22 端口)每秒最多 3 个新连接:

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

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j DROP

说明:

  • --limit 3/sec:平均每秒 3 个包
  • --limit-burst 5:突发最多 5 个

2. 限制 ICMP(ping)速率

防止 ping flood:

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

iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

3. 限制某 IP 的访问频率

限制来自 192.168.1.100 的 HTTP 请求:

iptables -A INPUT -s 192.168.1.100 -p tcp --dport 80 \
  -m limit --limit 10/min -j ACCEPT

iptables -A INPUT -s 192.168.1.100 -p tcp --dport 80 -j DROP

二、使用 iptables + hashlimit(更精细限速)

限制每个 IP 的 HTTP 连接速率

每个 IP 每秒最多 5 个新连接:

iptables -A INPUT -p tcp --dport 80 -m state --state NEW \
  -m hashlimit \
  --hashlimit-mode srcip \
  --hashlimit-upto 5/sec \
  --hashlimit-burst 10 \
  --hashlimit-name http_limit \
  -j ACCEPT

iptables -A INPUT -p tcp --dport 80 -m state --state NEW -j DROP

三、真正的“带宽限速”(推荐用 tc)

iptables 本身不能限制带宽(如 1Mbps),只能限制包速率。

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

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

查看:

tc qdisc show dev eth0

删除:

tc qdisc del dev eth0 root

四、CentOS 7 注意事项

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

保存规则:

service iptables save

总结

需求 推荐方式
防暴力破解 iptables limit
限制单 IP 频率 hashlimit
限制带宽 tc
简单包限速 iptables limit

如果你能说明:

  • CentOS 版本
  • 内网/外网
  • 限速对象(IP / 端口 / 协议)
  • 想要“包限速”还是“带宽限速”

我可以给你一条直接可执行的命令

0