启用或禁用SELinux的方法

SELinux 介绍:

  • SELinux是Security-Enhanced Linux的缩写。
  • 它就像Windows防火墙,但它更安全,更私密。它管理所有的访问控制策略。
  • 我们可以通过使用一些直接命令或实际进入SELinux配置文件并编辑状态来控制SELinux安全性的状态。
  • SELinux有三个值: enforcing, permissive and disabled。
  • Enforcing表示强制SELinux安全策略(强制模式)。Permissive表示SELinux不强制执行,但会打印警告(宽松模式)。Disabled表示不强制执行,也不打印警告(禁用,即SELinux停止工作)。

一般情况下,Linux管理员会把它disabled(例如:SELinux 不关闭,如修改ssh端口等策略不生效)。

参考How to Enable or Disable SELinux in Different Modes?

1 查看 SELinux的状态(如图所示的是Enforcing的状态):

  # getenforce

2 启用或者禁用SElinux的两种方法:

  • 使用命令(通常是强制/宽松模式的切换,宽松模式相当于临时关闭SELinux)
  • 编辑SELinux的配置文件(通常是更改为禁用状态,相当于永久关闭SELinux)

enforcing/permissive -> disabled 的切换是需要重启机器才能生效的 ,反之相同。SELinux启用状态下,宽松/强制模式可切换自如

使用命令:

  1. 直接使用setenforce + value
#setenforce Enforcing
#getenforce

#setenforce Permissive
#getenforce

  1. 你可以用1或者0来进行强制/宽松模式的切换,如下图,系统重启后还是会自动切回强制模式
#setenforce 0
#getenforce

编辑SELinux 配置文件(修改后需要重启机器才能生效)

  1. 使用vi editor 打开SELinux配置文件, 文件路径: /etc/selinux/config
vi /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

把状态更改为disabled后保存,之后再查看就会发现disabled:

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted

3 使用脚本关闭SELinux

可以在Shell脚本里写如下命令

setenforce 0
sed -i --follow-symlinks 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux

该命令生效后,如果要再次开启selinx,可能会遇到如下问题

博客: 关于sed -i 修改selinx的问题

无法正常的通过命令或者更改配置文件启用selinux
原因: sed -i 会破坏原有文件的软/硬链接
/etc/sysconfig/selinux文件用脚本修改后,已经不是/etc/selinux/config的链接文件,变成了普通文件,之后无论如何更改都不会生效

解决方法:

# rm -rf /etc/sysconfig/selinux 删除原软链接文件
# ln -s /etc/selinux/config /etc/sysconfig/selinux重新创建软链接文件
# ls -li |grep selinux 查看软链接文件是否生效
# cat /etc/sysconfig/selinux 看软链接文件内容是否和源文件一样
如果一样,修改SELinux=enforcing,重启后查看selinux状态
posted @ 2024-02-26 13:41  希望能摸鱼的凛耶酱  阅读(167)  评论(0编辑  收藏  举报