温馨提示×

debian防火墙怎么配置规则

小樊
40
2026-09-17 12:39:50
栏目: 智能运维

在 Debian 里“防火墙”通常指 iptables / nftables,以及更常用的前端工具 ufw。下面按使用场景从简到繁说明。


一、最推荐:使用 ufw(简单直观)

1. 安装 ufw

sudo apt update
sudo apt install ufw

2. 基本配置

# 默认拒绝入站,允许出站
sudo ufw default deny incoming
sudo ufw default allow outgoing

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

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

# 启用防火墙
sudo ufw enable

# 查看状态
sudo ufw status verbose

3. 常用规则示例

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

# 拒绝某 IP
sudo ufw deny from 192.168.1.200

# 删除规则
sudo ufw delete allow 80/tcp

二、使用 nftables(Debian 新版本默认)

1. 安装并启用

sudo apt install nftables
sudo systemctl enable nftables

2. 示例规则(/etc/nftables.conf)

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
        tcp dport 80 accept
        tcp dport 443 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(不推荐新系统使用)

# 清空规则
iptables -F

# 默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 允许本地和已建立连接
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 开放端口
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

保存(Debian):

apt install iptables-persistent
netfilter-persistent save

四、选择建议

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

如果你能告诉我:

  • Debian 版本(cat /etc/os-release
  • 服务器还是桌面
  • 想开放/限制哪些服务(SSH、Web、数据库等)

我可以给你一份可直接用的防火墙配置文件

0