在 CentOS 上使用 iptables 进行限速,通常是通过 limit 模块(限制包速率)或结合 tc(traffic control) 做更精确的带宽限速。下面按常见场景说明。
例如限制 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 个防止 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
限制来自 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
每个 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
iptables 本身不能限制带宽(如 1Mbps),只能限制包速率。
tc qdisc add dev eth0 root tbf rate 1mbit burst 32kbit latency 400ms
查看:
tc qdisc show dev eth0
删除:
tc qdisc del dev eth0 root
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 |
如果你能说明:
我可以给你一条直接可执行的命令。