在 Debian 系统中,防火墙规则通常通过 iptables 或 nftables 来配置。从 Debian 10(Buster)开始,系统默认推荐使用 nftables,但 iptables 仍然可用(作为兼容层)。此外,很多用户也会使用 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
# 允许某个 IP 访问所有端口
sudo ufw allow from 192.168.1.100
# 启用防火墙
sudo ufw enable
# 查看状态
sudo ufw status verbose
sudo ufw deny 23/tcp
sudo ufw delete allow 80/tcp
sudo iptables -L -n -v
# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT
# 允许已建立连接
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许 SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 允许 HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 设置默认策略(谨慎)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
sudo apt install iptables-persistent
sudo netfilter-persistent save
sudo apt install nftables
sudo systemctl enable nftables
sudo systemctl start nftables
编辑配置文件:
sudo nano /etc/nftables.conf
示例内容:
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0;
iif lo accept
ct state established,related accept
tcp dport 22 accept
tcp dport 80 accept
tcp dport 443 accept
reject
}
chain forward {
type filter hook forward priority 0;
drop
}
chain output {
type filter hook output priority 0;
accept
}
}
应用规则:
sudo nft -f /etc/nftables.conf
| 场景 | 推荐 |
|---|---|
| 新手 / 简单服务器 | ufw |
| 传统服务器 / 老脚本 | iptables |
| 新系统 / 长期维护 | nftables |
如果你愿意,可以告诉我:
我可以给你一套可直接用的完整规则。