在 Debian 上开启防火墙,常见做法有两种:使用 ufw(推荐新手) 或 直接使用 nftables / iptables(更底层)。下面按常用程度给你说明。
ufw 是 Debian 上最常用的防火墙管理工具,底层基于 iptables 或 nftables。
sudo apt update
sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22 # SSH
sudo ufw allow 80 # HTTP
sudo ufw allow 443 # HTTPS
sudo ufw enable
sudo ufw status verbose
⚠️ 注意:
- 如果是远程服务器,一定要先允许 SSH(22)再启用 ufw,否则可能断连。
- 停用防火墙:
sudo ufw disable
从 Debian 10(Buster)开始,nftables 是官方推荐的防火墙框架。
sudo apt install nftables
sudo systemctl enable nftables
sudo systemctl start nftables
sudo nft list ruleset
编辑配置文件:
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
查看是否已安装:
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 |
如果你愿意,可以告诉我:
我可以帮你给出完全可直接用的配置。