温馨提示×

Debian如何开启防火墙

小樊
40
2026-07-18 05:12:31
栏目: 智能运维

在 Debian 系统中,常用的防火墙方案是 UFW(Uncomplicated Firewall)(适合新手)或直接使用 iptables / nftables(更底层)。下面按常见场景给你说明。


一、使用 UFW(推荐,简单)

1. 安装 UFW

sudo apt update
sudo apt install ufw

2. 开启防火墙

sudo ufw enable

开启后,默认策略是:

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

⚠️ 注意:如果你是通过 SSH 远程连接服务器,建议先放行 SSH 端口,否则可能被断开。


3. 允许常用端口(示例)

允许 SSH(非常重要)

sudo ufw allow 22/tcp

如果是自定义 SSH 端口,例如 2222:

sudo ufw allow 2222/tcp

允许 HTTP / HTTPS

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

允许指定 IP 访问

sudo ufw allow from 192.168.1.100

4. 查看防火墙状态

sudo ufw status
sudo ufw status verbose

5. 关闭 / 重启 UFW

sudo ufw disable
sudo ufw reload

二、使用 iptables(传统方式)

1. 查看当前规则

sudo iptables -L

2. 允许 SSH(防止被踢出)

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

3. 允许本地回环

sudo iptables -A INPUT -i lo -j ACCEPT

4. 允许已建立连接

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

5. 设置默认策略

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

⚠️ iptables 规则重启后会丢失,需要安装持久化工具:

sudo apt install iptables-persistent

保存规则:

sudo netfilter-persistent save

三、Debian 10+ 的 nftables(新方案)

Debian 10 以后,nftables 是默认后端。

查看状态

sudo systemctl status nftables

启用 nftables

sudo systemctl enable nftables
sudo systemctl start nftables

一般配合 UFW 或直接编辑 /etc/nftables.conf


四、推荐方案总结

场景 推荐
新手 / 服务器 ✅ UFW
高级定制 iptables / nftables
Debian 10+ UFW 或 nftables

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

  • 你是 本地电脑 还是 云服务器
  • 是否 远程 SSH
  • Debian 版本(cat /etc/debian_version

我可以给你一套最安全、不会断网的防火墙配置

0