在建站的过程中遇到了许多需要使用和修改CentOS上防火墙firewalld的问题,再此集中总结记录一下~
1. 安装及基本使用
1.1. 安装防火墙
如果系统中没有安装防火墙,我们需要用系统的包管理器安装一下,这里以CentOS 8的 yum 为例
yum install firewalld
1.2. 开启关闭防火墙
设置/取消随系统启动防火墙
systemctl enable firewalld
systemctl disable firewalld
手动开启/关闭防火墙
systemctl start firewalld
systemctl stop firewalld
1.3. 检查防火墙运行状态
有两种方式检查防火墙是否正常运行
- 使用
firewall-cmd --state
,提示running
$ firewall-cmd --state
running
- 使用
systemctl
$ systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2020-05-14 06:44:20 UTC; 11min ago
Docs: man:firewalld(1)
Main PID: 2970 (firewalld)
Tasks: 2 (limit: 5928)
Memory: 22.3M
CGroup: /system.slice/firewalld.service
└─2970 /usr/libexec/platform-python -s /usr/sbin/firewalld --nofork --nopid
1.4. 防火墙重启
$ firewall-cmd --reload
success
2. 配置防火墙
2.1. 开放/取消端口或协议
我们先看一个简单的例子:
$ firewall-cmd --zone=public --add-port=3000/tcp --permanent #允许在public zone永久开放基于tcp协议的3000端口
success
我们可以看到这条命令中有两个可选参数:
--zone=防火墙区域
:(可选)表示规则作用的区域。public为防火墙初始的默认的区域(默认区域可以通过--set-default-zone
修改)。其他区域还有internal
、home
等等,具体详见官网文档 - Zone,不添加此参数则规则将作用在默认区域上--permanent
:(可选)包含这个参数视为永久规则,防火墙重启后(--reload
)生效;不添加此参数则为临时生效规则,防火墙重启后还原
必选参数:
-
--add-port=端口号N/协议名P
:表示开启基于P协议的端口N,端口号协议名缺一不可。 -
--remove-port=端口号N/协议名P
:表示开启基于P协议的端口N,端口号协议名缺一不可。 -
--add-service=协议名P
:表示开启基于P协议的默认端口。 -
--remove-service=协议名P
:表示关闭基于P协议的默认端口。
以上参数无前后顺序限制,大家可
随意自行排列组合
再来几个栗子
# 在默认区域临时开放upd协议的5000端口
firewall-cmd --add-port=5000/udp
# 在默认区域永久关闭tcp协议的3000端口
firewall-cmd --remove-port=5000/udp --permanent
# 在internal区域临时开放ftp/sftp协议
firewall-cmd --add-service=ftp --zone=internal
# 在默认区域永久开放https协议
firewall-cmd --add-port=5000/udp --permanent
# 在home区域永久关闭http协议
firewall-cmd --permanent --zone=home --remove-service=http
开发中遇到过的其他注意点:
- WebSock基于TCP协议
- sftp也属于FTP协议
To be continued...