Linux 防火墙命令清单,覆盖 iptables、nftables、firewalld(CentOS/RHEL)和 ufw(Ubuntu/Debian)等常用工具:
防火墙管理命令
1. iptables(传统防火墙工具)
| 命令 | 备注 |
|---|---|
| iptables -L | 查看所有规则 |
| iptables -A INPUT -p tcp --dport 80 -j ACCEPT | 允许 TCP 80 端口入站 |
| iptables -A INPUT -s 192.168.1.100 -j DROP | 阻止来自指定 IP 的流量 |
| iptables -D INPUT 2 | 删除 INPUT 链中的第 2 条规则 |
| iptables-save > /etc/iptables/rules.v4 | 保存规则(需安装 iptables-persistent) |
| iptables-restore < /etc/iptables/rules.v4 | 恢复已保存的规则 |
2. nftables(新一代防火墙工具)
| 命令 | 备注 |
|---|---|
| nft list ruleset | 查看所有规则 |
| nft add table inet my_table | 创建新表 |
| nft add chain inet my_table my_chain { type filter hook input priority 0 ; } | 创建链并绑定到 INPUT 钩子 |
| nft add rule inet my_table my_chain tcp dport 22 accept | 允许 SSH 端口(22)入站 |
| nft delete rule inet my_table my_chain handle 5 | 删除指定句柄的规则 |
| nft flush ruleset | 清空所有规则 |
3. firewalld(CentOS/RHEL/Fedora)
| 命令 | 备注 |
|---|---|
| firewall-cmd --state | 查看防火墙状态 |
| firewall-cmd --list-all | 查看所有规则和区域配置 |
| firewall-cmd --zone=public --add-port=80/tcp --permanent | 永久开放 TCP 80 端口 |
| firewall-cmd --zone=public --remove-port=22/tcp --permanent | 永久关闭 SSH 端口(22) |
| firewall-cmd --zone=public --add-source=192.168.1.0/24 --permanent | 允许指定 IP 段的流量 |
| firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.5.103" reject' | 阻止指定IP的流量 |
| firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="192.168.5.103" reject' | 永久删除阻止指定ip的流量rule |
| firewall-cmd --permanent --remove-rich-rule='rule family="ipv4" source address="10.8.0.0/24" destination address="192.168.0.107" port port="8090" protocol="tcp" accept' | 永久删除vpnip转发rule |
| firewall-cmd --reload | 重载配置(应用永久规则) |
| systemctl start firewalld | 启动防火墙 |
| systemctl stop firewalld | 停止防火墙 |
| systemctl enable firewalld | 开机自启 |
| systemctl status firewalld | 查看防火墙状态 |
| systemctl disable firewalld | 开机关闭 |
4. ufw(Ubuntu/Debian 简化工具)
| 命令 | 备注 |
|---|---|
| ufw reload | 重新加载规则 |
| ufw disable | 禁用防火墙 |
| ufw status numbered | 查看规则(带编号) |
| ufw allow 80/tcp | 允许 TCP 80 端口 |
| ufw deny from 192.168.1.100 | 阻止指定 IP 的流量 |
| ufw delete 2 | 删除编号为 2 的规则 |
| ufw reset | 重置防火墙(清空所有规则) |
常见操作场景
- 开放 Web 服务端口(HTTP/HTTPS) # firewalld firewall-cmd --permanent --add-service=http --add-service=https firewall-cmd --reload # ufw ufw allow 80/tcp ufw allow 443/tcp
- 允许特定 IP 访问 SSH # iptables iptables -A INPUT -p tcp --dport 22 -s 192.168.0.100 -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j DROP # ufw ufw allow from 192.168.0.100 to any port 22
- 阻止 ICMP(Ping)请求 # iptables iptables -A INPUT -p icmp --icmp-type echo-request -j DROP # firewalld firewall-cmd --add-icmp-block=echo-request --permanent firewall-cmd --reload
注意事项
- 规则优先级:防火墙规则按顺序匹配,第一条匹配的规则生效。
- 持久化保存:
- iptables 需手动保存规则(如 iptables-save)。
- firewalld 和 ufw 的 --permanent 参数可永久保存规则。
- 谨慎操作:避免通过防火墙规则封锁自己的 SSH 连接!