Centos防火墙的一键开启与关闭

知识铺垫

一、防火墙的开启、关闭、禁用命令

(1)设置开机启用防火墙:systemctl enable firewalld.service

(2)设置开机禁用防火墙:systemctl disable firewalld.service

(3)启动防火墙:systemctl start firewalld

(4)关闭防火墙:systemctl stop firewalld

(5)检查防火墙状态:systemctl status firewalld

二、使用firewall-cmd配置端口

(1)查看防火墙状态:firewall-cmd --state

(2)重新加载配置:firewall-cmd --reload

(3)查看开放的端口:firewall-cmd --list-ports

(4)开启防火墙端口:firewall-cmd --zone=public --add-port=端口号/tcp --permanent

  注意:添加端口后,必须用命令firewall-cmd --reload重新加载一遍才会生效

(5)关闭防火墙端口:firewall-cmd --zone=public --remove-port=9200/tcp --permanent

shell脚本全文

#!/bin/bash

#Centos8 firewall防火墙关闭/开启的shell脚本

#判断当前用户是否为root
who | cut -d' ' -f1 | sort | uniq > $USER

if [[ $USER = root ]]; then
#查看当前Firewalls的状态
    STATE=`firewall-cmd --state`
#在Firewalls开启时,执行本脚本则关闭Firewalls
    if [[ $STATE = "running" ]]; then
        systemctl stop firewalld.service
        echo -e "当前Firewalls状态为:not running"
#在Firewalls关闭时,执行本脚本则开启Firewalls;
    else
        systemctl start firewalld.service
        STATE_OPEN=`firewall-cmd --state`
        echo -e "当前Firewalls状态为:$STATE_OPEN"
    fi
else
    echo "当前非root用户,请切换权限。"
fi

实际环境演示

[gaohui@localhost ~]$ ./firewall.sh 
当前非root用户,请切换权限。
[gaohui@localhost ~]$ su -
密码:
[root@localhost ~]# cd /home/gaohui/
[root@localhost gaohui]# ./firewall.sh 
当前Firewalls状态为:not running
[root@localhost gaohui]# ./firewall.sh 
not running
当前Firewalls状态为:running
[root@localhost gaohui]# firewall-cmd --state 
running

你可能感兴趣的:(Linux,centos,网络,运维)