温馨提示×

linux防火墙怎么添加规则

小樊
45
2026-10-10 05:04:55
栏目: 智能运维

在 Linux 中,防火墙规则取决于你使用的防火墙工具。常见有以下几种:


一、使用 iptables(传统方式)

1. 查看规则

iptables -L -n -v

2. 添加规则(示例)

允许 SSH(22端口)

iptables -A INPUT -p tcp --dport 22 -j ACCEPT

允许某个 IP 访问所有端口

iptables -A INPUT -s 192.168.1.100 -j ACCEPT

禁止某个 IP

iptables -A INPUT -s 10.0.0.5 -j DROP

允许已建立连接

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

3. 保存规则

# CentOS / RHEL
service iptables save

# Ubuntu(需安装)
iptables-save > /etc/iptables.rules

二、使用 firewalld(CentOS 7+ / RHEL / Fedora)

1. 查看状态

systemctl status firewalld

2. 添加端口规则

firewall-cmd --zone=public --add-port=8080/tcp --permanent
firewall-cmd --reload

3. 允许服务(如 http)

firewall-cmd --add-service=http --permanent
firewall-cmd --reload

4. 允许指定 IP

firewall-cmd --permanent --add-source=192.168.1.0/24
firewall-cmd --reload

三、使用 ufw(Ubuntu 常用)

1. 启用防火墙

ufw enable

2. 添加规则

ufw allow 22/tcp
ufw allow 80
ufw deny 3306

3. 允许指定 IP

ufw allow from 192.168.1.100

4. 查看规则

ufw status

四、快速选择建议

系统 推荐
CentOS 7+ firewalld
Ubuntu ufw
老系统 / 精细控制 iptables

如果你能告诉我:

  • 使用的 Linux 发行版
  • 想实现什么(开放端口 / 封 IP / 限制访问)

我可以给你精确命令。

0 踩