在 Debian 里“防火墙”通常指 iptables / nftables,以及更常用的前端工具 ufw。下面按使用场景从简到繁说明。
sudo apt update
sudo apt install ufw
# 默认拒绝入站,允许出站
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
# 允许某 IP 访问所有端口
sudo ufw allow from 192.168.1.100
# 拒绝某 IP
sudo ufw deny from 192.168.1.200
# 删除规则
sudo ufw delete allow 80/tcp
sudo apt install nftables
sudo systemctl enable nftables
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 -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 |
如果你能告诉我:
cat /etc/os-release)我可以给你一份可直接用的防火墙配置文件。