在 Debian 系统中,添加防火墙规则通常使用 iptables 或 nftables,不过 Debian 10(Buster)及以后版本更推荐使用 nftables。下面分别介绍几种常见方式。
ufw(最简单,推荐新手)ufw(Uncomplicated Firewall)是基于 iptables/nftables 的简化工具。
sudo apt update
sudo apt install ufw
sudo ufw enable
✅ 允许 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
sudo ufw status verbose
iptables(传统方式)sudo apt install iptables
✅ 允许 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
Debian 不会自动保存 iptables 规则。
sudo apt install iptables-persistent
sudo netfilter-persistent save
nftables(Debian 官方推荐)sudo apt install nftables
sudo systemctl enable nftables
sudo systemctl start nftables
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
sudo nft list ruleset > /etc/nftables.conf
| 场景 | 推荐 |
|---|---|
| 新手 / 简单服务器 | ✅ ufw |
| 传统系统 | iptables |
| 新系统 / 长期维护 | ✅ nftables |
如果你愿意,可以告诉我:
cat /etc/debian_version)我可以帮你定制一套完整防火墙规则 ✅