在 Debian 系统中,配置防火墙通常有几种常见方式,最常用的是 iptables(传统) 和 nftables(新一代,Debian 10+ 默认),以及更友好的前端工具 ufw。下面按使用场景给你说明。
sudo apt update
sudo apt install ufw
# 允许 SSH(非常重要,避免被锁外面)
sudo ufw allow 22/tcp
# 允许 HTTP / HTTPS
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 拒绝所有入站,允许所有出站
sudo ufw default deny incoming
sudo ufw default allow outgoing
# 启用防火墙
sudo ufw enable
# 查看状态
sudo ufw status verbose
sudo ufw allow 3306/tcp # 允许 MySQL
sudo ufw delete allow 80/tcp # 删除规则
sudo ufw disable # 关闭
sudo apt install nftables
sudo systemctl enable nftables
table inet filter {
chain input {
type filter hook input priority 0;
# 允许本地回环
iif lo accept
# 已建立连接允许
ct state established,related accept
# 允许 SSH
tcp dport 22 accept
# 允许 Web
tcp dport {80, 443} accept
# 拒绝其他
drop
}
chain forward {
type filter hook forward priority 0;
drop
}
chain output {
type filter hook output priority 0;
accept
}
}
sudo nft -f /etc/nftables.conf
Debian 新版本已逐步用 nftables 替代 iptables
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -P INPUT DROP
保存规则:
sudo apt install iptables-persistent
sudo netfilter-persistent save
如果你愿意,可以告诉我:
cat /etc/debian_version)我可以直接帮你写一套可复制的防火墙配置。