温馨提示×

centos防火墙怎样添加规则

小樊
48
2026-09-14 23:31:47
栏目: 智能运维

在 CentOS 中,防火墙主要有两种方式:firewalld(CentOS 7 及以后推荐) 和 iptables(传统方式)。下面分别说明。


一、使用 firewalld(CentOS 7/8/Stream 推荐)

1. 查看防火墙状态

systemctl status firewalld
# 或
firewall-cmd --state

2. 启动 / 开机自启

systemctl start firewalld
systemctl enable firewalld

3. 添加端口规则(常用)

# 开放 TCP 8080 端口(临时)
firewall-cmd --add-port=8080/tcp

# 永久生效
firewall-cmd --add-port=8080/tcp --permanent

# 重新加载规则
firewall-cmd --reload

4. 添加服务规则

# 开放 http 服务
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

5. 查看已添加规则

firewall-cmd --list-all
firewall-cmd --list-ports

6. 删除规则

firewall-cmd --remove-port=8080/tcp --permanent
firewall-cmd --reload

7. 指定 IP 允许访问某端口

firewall-cmd --permanent --add-rich-rule='
rule family="ipv4"
source address="192.168.1.100"
port protocol="tcp" port="3306" accept'
firewall-cmd --reload

二、使用 iptables(CentOS 6 或手动关闭 firewalld)

1. 安装 iptables(如未安装)

yum install iptables-services -y
systemctl stop firewalld
systemctl disable firewalld
systemctl start iptables

2. 添加规则

# 允许 8080 端口
iptables -I INPUT -p tcp --dport 8080 -j ACCEPT

# 保存规则
service iptables save
# 或
iptables-save > /etc/sysconfig/iptables

3. 查看规则

iptables -L -n

三、常见示例

  • 开放 SSH(22):
firewall-cmd --add-service=ssh --permanent
  • 禁止某 IP:
firewall-cmd --permanent --add-rich-rule='rule family=ipv4 source address=10.0.0.5 reject'

如果你能说明 CentOS 版本 和 具体需求(端口 / IP / 服务),我可以给你更精确的命令。

0 踩