温馨提示×

linux防火墙怎样管理规则

小樊
52
2026-10-28 00:31:42
栏目: 智能运维

在 Linux 里,“防火墙”通常分两层来看:

  1. iptables / nftables:真正的内核级包过滤机制
  2. firewalld / ufw:面向用户的“管理工具”,底层还是 iptables 或 nftables

下面按常见场景系统讲一下。


一、先确认你用的是什么

# 查看是否有 firewalld
systemctl status firewalld

# 查看是否有 ufw(Ubuntu 常见)
ufw status

# 查看底层规则
iptables -L -n
nft list ruleset

常见组合:

  • CentOS / RHEL 7+:firewalld(底层 nftables/iptables)
  • Ubuntu:ufw(底层 iptables)
  • 手动服务器 / 容器宿主机:直接 iptables / nftables

二、使用 firewalld(CentOS / RHEL)

1. 基本状态

systemctl start firewalld
systemctl enable firewalld
firewall-cmd --state

2. 查看规则

firewall-cmd --list-all
firewall-cmd --list-ports
firewall-cmd --list-services

3. 添加 / 删除端口(临时 + 永久)

# 开放 8080 TCP(临时)
firewall-cmd --add-port=8080/tcp

# 永久
firewall-cmd --add-port=8080/tcp --permanent

# 删除
firewall-cmd --remove-port=8080/tcp --permanent

4. 管理服务(预定义)

firewall-cmd --add-service=http --permanent
firewall-cmd --reload

5. 重载规则

firewall-cmd --reload

三、使用 ufw(Ubuntu 推荐)

1. 启用

ufw enable
ufw status verbose

2. 管理规则

# 允许
ufw allow 22/tcp
ufw allow 80

# 拒绝
ufw deny 3306

# 删除
ufw delete allow 22/tcp

3. 默认策略

ufw default deny incoming
ufw default allow outgoing

四、直接使用 iptables(高级 / 手动)

1. 查看规则

iptables -L -n -v

2. 添加规则

# 允许 SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许已建立连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 拒绝其他
iptables -P INPUT DROP

3. 保存规则

# CentOS
service iptables save

# Ubuntu
iptables-save > /etc/iptables.rules

⚠️ iptables 重启会丢规则,必须保存。


五、nftables(新趋势)

nft list ruleset

nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; }
nft add rule inet filter input tcp dport 22 accept

六、日常管理建议

✅ 改规则前先留 SSH 通道
✅ 用 --permanent + --reload
✅ 禁止直接 DROP 所有 INPUT 而不允许 ESTABLISHED
✅ 云服务器注意“安全组 + 防火墙”双层


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

  • 你用的是 哪个 Linux 发行版
  • 是 服务器还是云主机
  • 想实现什么(开放端口 / 限制 IP / 防攻击)

我可以直接给你一套可复制的命令。

0 踩