温馨提示×

怎么设置Debian防火墙

小樊
43
2026-08-17 04:36:03
栏目: 智能运维

在 Debian 系统中,常用的防火墙方案是 UFW(Uncomplicated Firewall),它是对 iptables 的简化封装,适合大多数用户。如果你需要更底层控制,也可以直接使用 iptablesnftables。下面我按推荐程度给你讲。


一、使用 UFW(推荐 ✅)

1. 安装 UFW

sudo apt update
sudo apt install ufw

2. 查看状态

sudo ufw status

3. 设置默认策略(建议)

sudo ufw default deny incoming
sudo ufw default allow outgoing

含义:

  • 拒绝所有入站连接
  • 允许所有出站连接

4. 允许常用端口

sudo ufw allow 22        # SSH
sudo ufw allow 80        # HTTP
sudo ufw allow 443       # HTTPS

也可以指定协议:

sudo ufw allow 22/tcp

5. 允许特定 IP

sudo ufw allow from 192.168.1.100

6. 删除规则

sudo ufw delete allow 22

7. 启用 / 禁用防火墙

sudo ufw enable
sudo ufw disable

⚠️ 注意:启用前确保 SSH 端口已放行,否则可能被锁在外面。


二、使用 iptables(传统方式)

1. 查看当前规则

sudo iptables -L

2. 示例:放行 SSH

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

3. 保存规则(Debian 10+)

sudo apt install iptables-persistent
sudo netfilter-persistent save

三、使用 nftables(新一代,Debian 10+ 推荐)

1. 安装

sudo apt install nftables

2. 查看规则

sudo nft list ruleset

3. 示例配置

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

4. 开机自启

sudo systemctl enable nftables

四、推荐方案总结

场景 推荐
新手 / 服务器 ✅ UFW
高级定制 nftables
老系统 iptables

五、安全建议 ⚠️

  • 启用防火墙前 先放行 SSH
  • 云服务器建议配合 安全组
  • 不要同时混用 UFW + iptables + nftables

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

  • Debian 版本(cat /etc/debian_version
  • 本地服务器 / 云服务器 / 桌面
  • 是否需要 Docker / 科学上网 / 多端口

我可以帮你给出完整可用的防火墙配置方案

0