在 CentOS 7 中,防火墙的配置和管理通常使用 firewalld 服务来完成。firewalld 提供了一个动态的防火墙解决方案,可以根据系统的运行状态和应用程序的需求自动调整防火墙规则。
常用的 CentOS 7 防火墙配置操作:
启动和停止 firewalld 服务
启动服务:
systemctl start firewalld
停止服务:
systemctl stop firewalld
检查 firewalld
systemctl status firewalld
开启端口
使用以下命令开启指定端口(例如,开启 SSH 服务的 22 端口):
firewall-cmd --permanent --add-port=22/tcp firewall-cmd --reload
关闭端口
使用以下命令关闭指定端口(例如,关闭 SSH 服务的 22 端口):
firewall-cmd --permanent --remove-port=22/tcp firewall-cmd --reload
允许或拒绝特定协议和端口范围
使用以下命令允许或拒绝特定协议和端口范围(例如,允许 TCP 协议的 80-90 端口范围):
firewall-cmd --permanent --add-port=80-90/tcp firewall-cmd --reload
允许或拒绝特定服务
使用以下命令允许或拒绝特定服务(例如,允许 SSH 服务):
firewall-cmd --permanent --add-service=ssh firewall-cmd --reload
查看防火墙规则列表
使用以下命令查看当前的防火墙规则列表:
firewall-cmd --list-all
举几个常用的 CentOS 7 防火墙配置例子:
允许 HTTP(80 端口)和 HTTPS(443 端口)通过防火墙:
firewall-cmd --permanent --add-port=80/tcp firewall-cmd --permanent --add-port=443/tcp firewall-cmd --reload
禁止 ICMP 协议通过防火墙:
firewall-cmd --permanent --remove-protocol=icmp firewall-cmd --reload
添加自定义规则以允许特定 IP 地址访问特定端口:
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port protocol="tcp" port="8080" accept
firewall-cmd --reload
禁止特定 IP 地址访问服务器:
firewall-cmd --permanent --remove-source=192.168.1.100 firewall-cmd --reload
重新加载防火墙配置以使更改生效:
firewall-cmd --reload
请注意,上述命令中的 –permanent 选项表示将规则保存到防火墙的永久配置中,如果不使用该选项,规则将在重启后失效。
最后,我们整理了几个最常用的命令:查询、开放、关闭端口
查询端口是否开放
firewall-cmd --query-port=8080/tcp
开放80端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
移除端口
firewall-cmd --permanent --remove-port=8080/tcp
重启防火墙(修改配置后要重启防火墙)
firewall-cmd --reload
参数解释
firwall-cmd是Linux提供操作firewall的一个工具;
--permanent:表示设置为持久;
--add-port:标识添加的端口;