温馨提示×

如何添加Debian防火墙规则

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

在 Debian 系统中,添加防火墙规则通常使用 iptablesnftables,不过 Debian 10(Buster)及以后版本更推荐使用 nftables。下面分别介绍几种常见方式。


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

ufw(Uncomplicated Firewall)是基于 iptables/nftables 的简化工具。

1. 安装 ufw

sudo apt update
sudo apt install ufw

2. 启用 ufw

sudo ufw enable

3. 添加防火墙规则示例

✅ 允许 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 allow 3000:4000/tcp

4. 查看规则

sudo ufw status verbose

二、使用 iptables(传统方式)

1. 安装 iptables(通常已安装)

sudo apt install iptables

2. 添加规则示例

✅ 允许 SSH

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

✅ 允许 HTTP

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

✅ 允许已建立连接

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

✅ 设置默认策略(谨慎)

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

3. 保存规则(非常重要)

Debian 不会自动保存 iptables 规则。

sudo apt install iptables-persistent
sudo netfilter-persistent save

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

1. 安装 nftables

sudo apt install nftables

2. 启用 nftables

sudo systemctl enable nftables
sudo systemctl start nftables

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
sudo nft add rule inet filter input tcp dport 80 accept

4. 保存规则

sudo nft list ruleset > /etc/nftables.conf

四、选择建议

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

五、⚠️ 注意事项

  1. 修改 SSH 端口前先测试
  2. 不要直接 DROP INPUT,避免断连
  3. 云服务器需同时检查安全组规则
  4. 规则修改后测试再退出终端

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

  • Debian 版本(cat /etc/debian_version
  • 是本地服务器还是云服务器
  • 想开放/限制哪些端口

我可以帮你定制一套完整防火墙规则 ✅

0