centos开放防火墙端口
centos 防火墙端口
在 CentOS 系统中,防火墙的管理通常是通过 firewalld 或 iptables 这两个服务来实现的。下面我将分别介绍如何使用这两个工具来开放或管理防火墙端口。
使用 firewalld
安装 firewalld(如果尚未安装):
sudo yum install firewalld
启动 firewalld 服务:
sudo systemctl start firewalld
启用 firewalld 开机自启:
sudo systemctl enable firewalld
开放端口:
永久开放端口:
sudo firewall-cmd --zone=public --add-port=端口号/tcp --permanent
例如,开放 8080 端口:
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
立即生效(无需重启服务):
sudo firewall-cmd --reload
查看开放的端口:
sudo firewall-cmd --list-ports
使用 iptables
安装 iptables(通常 CentOS 7 以上版本默认已安装):
sudo yum install iptables-services
启动 iptables 服务:
sudo systemctl start iptables
启用 iptables 开机自启:
sudo systemctl enable iptables
开放端口:
添加规则永久开放端口:
sudo iptables -I INPUT -p tcp --dport 端口号 -j ACCEPT
例如,开放 8080 端口:
sudo iptables -I INPUT -p tcp --dport 8080 -j ACCEPT
保存规则(CentOS 7 及以下版本):
sudo service iptables save
CentOS 8 使用 firewalld 作为默认防火墙,如果要使用 iptables,需要禁用 firewalld:
sudo systemctl stop firewalld
sudo systemctl disable firewalld
CentOS 8 中保存规则:
sudo iptables-save > /etc/sysconfig/iptables
查看开放的端口:
sudo iptables -L -n --line-numbers
注意事项:
在 CentOS 8 中,默认使用的是 firewalld,如果要使用 iptables,需要禁用 firewalld。在 CentOS 7 及以下版本,iptables 和 firewalld 可以共存,但通常只需要选择一个来管理防火墙规则。如果你选择使用 iptables,确保禁用 firewalld。
在执行任何防火墙规则更改后,确保重新加载或重启相应的服务以使更改生效。对于 firewalld,使用 sudo firewall-cmd --reload;对于 iptables 在 CentOS 7 及以下版本中,可以使用 sudo service iptables restart 或 sudo systemctl restart iptables。在 CentOS 8 中,由于使用了 firewalld,通常不需要重启 iptables 服务。