CentOS7防火墙放行或限制指定IP和端口(firewall)
CentOS7默认没有安装iptables,可以手动安装iptables;也可以通过CentOS7已带的firewall配置防火墙。
1.查看firewalld.service服务状态
systemctl status firewalld
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425143859916-1180253091.png)
2.查看firewall运行状态
firewall-cmd --state
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425144133331-260096527.png)
3.手动启动/停止/重启firewalld.service服务
# 启动firewalld service firewalld start # 停止firewalld service firewalld stop # 重启firewalld service firewalld restart
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425144643946-1628724427.png)
4.展示当前配置的firewall规则
firewall-cmd --list-all
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425144757033-1048957201.png)
5.端口(端口段)的查询/开放
# 查询端口是否开放 firewall-cmd --query-port=8080/tcp # 新建永久规则,开放8080端口(TCP协议) firewall-cmd --permanent --add-port=8080/tcp # 移除上述规则 firewall-cmd --permanent --remove-port=8080/tcp # 新建永久规则,批量开放一段端口(TCP协议) firewall-cmd --permanent --add-port=9001-9100/tcp
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425150111085-1053856577.png)
6.IP(IP段)的开放
# 新建永久规则,开放192.168.1.1单个源IP的访问 firewall-cmd --permanent --add-source=192.168.1.1 # 新建永久规则,开放192.168.1.0/24整个源IP段的访问 firewall-cmd --permanent --add-source=192.168.1.0/24 # 移除上述规则 firewall-cmd --permanent --remove-source=192.168.1.1
![](https://img2020.cnblogs.com/blog/1115496/202104/1115496-20210425150330251-396318071.png)
7.系统服务的开放
# 开放http服务 firewall-cmd --permanent --add-service=http # 移除上述规则 firewall-cmd --permanent --remove-service=http
8.自定义复杂规则(注意是否与已有规则冲突)
# 允许指定IP访问本机8080端口 firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.1" port protocol="tcp" port="8080" accept' # 允许指定IP段访问本机8080-8090端口 firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="8080-8090" accept' # 禁止指定IP访问本机8080端口 firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.1" port protocol="tcp" port="8080" reject'
9.任何修改操作,配置完成后,需要重新装载firewall。可重新启动firewalld服务。
firewall-cmd --reload
service firewalld restart