温馨提示×

Debian防火墙规则如何设

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

在 Debian 系统中,防火墙规则通常通过 iptablesnftables 来配置。从 Debian 10(Buster)开始,系统默认推荐使用 nftables,但 iptables 仍然可用(作为兼容层)。此外,很多用户也会使用 ufw(简单防火墙)来简化操作。

下面分几种常见方式来说明。


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

1. 安装 ufw

sudo apt update
sudo apt install ufw

2. 基本用法

# 允许 SSH(非常重要,避免被锁外面)
sudo ufw allow 22/tcp

# 允许 HTTP / HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 允许某个 IP 访问所有端口
sudo ufw allow from 192.168.1.100

# 启用防火墙
sudo ufw enable

# 查看状态
sudo ufw status verbose

3. 禁止/删除规则

sudo ufw deny 23/tcp
sudo ufw delete allow 80/tcp

二、使用 iptables(传统方式)

1. 查看当前规则

sudo iptables -L -n -v

2. 示例规则

# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT

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

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

# 允许 HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 设置默认策略(谨慎)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

3. 保存规则(Debian 不会自动保存)

sudo apt install iptables-persistent
sudo netfilter-persistent save

三、使用 nftables(Debian 官方推荐)

1. 安装并启用

sudo apt install nftables
sudo systemctl enable nftables
sudo systemctl start nftables

2. 示例配置

编辑配置文件:

sudo nano /etc/nftables.conf

示例内容:

#!/usr/sbin/nft -f

flush ruleset

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

        iif lo accept
        ct state established,related accept

        tcp dport 22 accept
        tcp dport 80 accept
        tcp dport 443 accept

        reject
    }

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

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

应用规则:

sudo nft -f /etc/nftables.conf

四、如何选择?

场景 推荐
新手 / 简单服务器 ufw
传统服务器 / 老脚本 iptables
新系统 / 长期维护 nftables

五、重要提醒 ⚠️

  • 配置 SSH 规则后再启用 DROP 策略
  • 云服务器建议配合 安全组
  • 修改规则前可开一个额外 SSH 会话测试

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

  • Debian 版本
  • 是物理机 / 云服务器 / 容器
  • 需要开放哪些端口或服务

我可以给你一套可直接用的完整规则

0