温馨提示×

如何开启Debian防火墙

小樊
45
2026-08-17 04:32:04
栏目: 智能运维

Debian 上开启防火墙,常见做法有两种:使用 ufw(推荐新手)直接使用 nftables / iptables(更底层)。下面按常用程度给你说明。


一、使用 ufw(最简单,推荐)

ufw 是 Debian 上最常用的防火墙管理工具,底层基于 iptablesnftables

1. 安装 ufw

sudo apt update
sudo apt install ufw

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

sudo ufw default deny incoming
sudo ufw default allow outgoing

3. 放行常用端口(按需)

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

4. 启用防火墙

sudo ufw enable

5. 查看状态

sudo ufw status verbose

⚠️ 注意

  • 如果是远程服务器,一定要先允许 SSH(22)再启用 ufw,否则可能断连。
  • 停用防火墙:
sudo ufw disable

二、使用 nftables(Debian 10+ 推荐)

从 Debian 10(Buster)开始,nftables 是官方推荐的防火墙框架。

1. 安装 nftables

sudo apt install nftables

2. 启用并启动

sudo systemctl enable nftables
sudo systemctl start nftables

3. 查看当前规则

sudo nft list ruleset

4. 示例:允许 SSH 并拒绝其他入站

编辑配置文件:

sudo nano /etc/nftables.conf

示例内容:

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        ct state established,related accept
        iif lo accept
        tcp dport 22 accept
    }

    chain forward {
        type filter hook forward priority 0; policy drop;
    }

    chain output {
        type filter hook output priority 0; policy accept;
    }
}

应用规则:

sudo nft -f /etc/nftables.conf

三、使用 iptables(传统方式,不推荐新系统)

查看是否已安装:

sudo apt install iptables

示例(允许 SSH):

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

保存规则(Debian 默认不自动保存):

sudo apt install iptables-persistent
sudo netfilter-persistent save

四、如何选择?

场景 推荐
新手 / 普通服务器 ✅ ufw
新系统 / 想用现代方案 ✅ nftables
老系统 / 兼容旧脚本 iptables

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

  • 你用的是 Debian 几?
  • 本地电脑还是云服务器?
  • 是否需要 仅开放某些端口?

我可以帮你给出完全可直接用的配置

0