在 CentOS 7/8 及更高版本中,推荐使用 firewalld 作为默认防火墙管理工具,但如果你需要配置 iptables(例如为了兼容旧脚本、精细控制或特定需求),可以按以下步骤操作。
⚠️ 注意:CentOS 8 已停止维护,CentOS Stream 9 及 RHEL 系列更推荐使用
firewalld+nftables。若必须使用iptables,请确保系统已安装iptables-services包。
一、安装与启用 iptables 服务(如未安装)
# 检查是否已安装
rpm -qa | grep iptables
# 安装(CentOS 7/8)
sudo yum install -y iptables-services
# 启动并设置开机自启
sudo systemctl enable --now iptables
💡 若系统使用的是
firewalld,建议先停用它以避免冲突:sudo systemctl stop firewalld sudo systemctl disable firewalld
二、基础规则配置示例
1. 查看当前规则
sudo iptables -L -n -v
2. 允许 SSH(端口 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
3. 允许 HTTP/HTTPS(80/443)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
4. 允许 ICMP(ping)
sudo iptables -A INPUT -p icmp -j ACCEPT
5. 允许已建立连接的数据包返回
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
6. 拒绝其他所有入站流量(默认策略设为 DROP)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT # 通常出站无需限制
7. 保存规则(关键!否则重启后失效)
# CentOS 7:
sudo service iptables save
# CentOS 8+(若安装了 iptables-services):
sudo /sbin/iptables-save > /etc/sysconfig/iptables
✅ 验证保存结果:
cat /etc/sysconfig/iptables
三、常用进阶技巧
-
删除某条规则(按编号或内容):
sudo iptables -D INPUT -p tcp --dport 22 -j ACCEPT # 或按行号删除(第3条) sudo iptables -D INPUT 3 -
清空所有规则(谨慎操作):
sudo iptables -F # 清空过滤表规则 sudo iptables -X # 删除自定义链 sudo iptables -Z # 清零计数器 sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT -
限制 SSH 登录尝试频率(防暴力破解):
sudo iptables -A INPUT -p tcp --dport 22 -m recent --set --name SSH sudo iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
四、安全建议
- 务必先开放必要端口,再设置默认 DROP;
- 避免直接
DROP本地回环接口(lo),可加:sudo iptables -A INPUT -i lo -j ACCEPT - 生产环境建议配合
fail2ban增强防护; - 定期审计规则:
iptables-save | grep -E '^(COMMIT|:)'检查策略一致性。
如需图形化管理或简化操作,也可考虑迁移到 firewalld(更现代、动态、易用)。是否需要我提供对应的 firewalld 配置示例?
PHPWP博客