在Linux中复制文件时,如何保留SELinux上下文

SElinux现在已经成为Linux系统的重要组成部分。在各种服务的配置过程中,文件SELinux上下文起着重要的作用。有时,您需要使用预定义的SELinux上下文复制或者备份文件,以供以后使用,或者尝试模拟当前配置。

要在复制文件时保留SELinux上下文,使用带有“---preserve=context”选项的“cp”命令。

首先查看 /etc/services文件的SELinux文件上下文:

[root@rhel7 ]# ls -Z /etc/services 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /etc/services

在复制时,默认情况下,将创建一个新的selinux文件上下文:

[root@rhel7 ]# cp /etc/services /tmp/
[root@rhel7 ]# ls -Z /tmp/services 
-rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/services

cp命令使用preserve = context选项,将保留selinux上下文:

[root@rhel7 ]# cp --preserve=context /etc/services /tmp/
cp: overwrite ‘/tmp/services’? y
[root@rhel7 ]# ls -Z /tmp/services 
-rw-r--r--. root root system_u:object_r:etc_t:s0       /tmp/services

对于目录,同样适用:

[root@rhel7 ]# ls -Zd /etc/
drwxr-xr-x. root root system_u:object_r:etc_t:s0       /etc/
[root@rhel7 ]# cp -r /etc/ /tmp/
[root@rhel7 ]# ls -Zd /tmp/etc/
drwxr-xr-x. root root unconfined_u:object_r:user_tmp_t:s0 /tmp/etc/
[root@rhel7 ]# rm -fr /tmp/etc/
[root@rhel7 ]# cp -r --preserve=context /etc/ /tmp/
[root@rhel7 ]# ls -Zd /tmp/etc/
drwxr-xr-x. root root system_u:object_r:etc_t:s0       /tmp/etc/
日期:2020-07-07 20:54:57 来源:oir作者:oir