温馨提示×

centos iptables如何限制流量

小樊
37
2026-08-18 05:46:40
栏目: 智能运维

CentOS(使用 iptables) 中限制流量,常见手段有 限制连接数、限制速率(限速)、限制并发。下面按常用场景给你一个实用总结(含示例命令)。


一、限制连接速率(最常见:防攻击 / 限速)

1️⃣ 限制每秒新建连接数(防 CC / 扫描)

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

含义:

  • 每秒最多 10 个新连接
  • 突发允许 20 个
  • 超出部分 丢弃

✅ 常用于:

  • Web 服务(80 / 443)
  • SSH(22)

2️⃣ 限制 ICMP(ping)流量

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

防止 ping flood。


二、限制单 IP 并发连接数(防单 IP 打满)

1️⃣ 限制 SSH 并发连接

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

含义:

  • 单个 IP 最多 3 个 SSH 连接
  • 超过直接拒绝

2️⃣ 限制 Web 并发连接

iptables -A INPUT -p tcp --dport 80 \
-m connlimit --connlimit-above 20 -j REJECT

三、限制流量大小(带宽限速)

⚠️ iptables 本身不能直接限制带宽,但可配合 tc(Traffic Control) 使用。

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

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

这是 Linux 流量整形,不是 iptables,但生产环境常用。


四、限制某 IP 访问频率(综合示例)

限制某 IP 访问 Web 频率

iptables -A INPUT -s 192.168.1.100 -p tcp --dport 80 \
-m limit --limit 5/sec -j ACCEPT
iptables -A INPUT -s 192.168.1.100 -p tcp --dport 80 -j DROP

五、查看 & 删除规则

查看规则

iptables -L -n -v

删除规则(按编号)

iptables -L --line-numbers
iptables -D INPUT 3

六、CentOS 7 特别注意(firewalld)

CentOS 7 默认使用 firewalld,iptables 规则可能被覆盖。

✅ 建议:

systemctl stop firewalld
systemctl disable firewalld
yum install -y iptables-services
systemctl enable iptables
systemctl start iptables

七、推荐组合(生产常用)

SSH 防护

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

Web 防 CC

  • limit + connlimit
  • 配合 fail2ban

如果你愿意,可以告诉我:

  • ✅ CentOS 版本(6 / 7 / 8)
  • ✅ 限制的是 入站还是出站
  • ✅ 是 限速、防攻击还是限制某 IP

我可以给你一套 可直接用的完整规则

0