基本概念

iptables 是 Linux 上的防火墙工具,通过规则链(chain)来控制网络流量。

常用链

说明
INPUT进入本机的流量
OUTPUT从本机出去的流量
FORWARD经过本机转发的流量

基本操作

1
2
3
iptables -L                    # 查看当前规则
iptables -L -n -v # 详细显示(含计数)
iptables -F # 清空所有规则

常用规则

1
2
3
4
5
6
7
8
9
# 允许 SSH 连接
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许 HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 拒绝所有其他入站流量
iptables -A INPUT -j DROP

保存规则

1
2
3
4
5
# Debian/Ubuntu
iptables-save > /etc/iptables/rules.v4

# CentOS/RHEL
service iptables save