临时修改文件或目录的 SELinux 安全上下文。
chcon 直接改写 inode 上的 SELinux 标签,可以设置用户、角色、类型、级别,或用 --reference 复制另一个文件的上下文。-R 递归、-h 作用于符号链接本身、-v 输出每个处理结果。它要求系统启用了 SELinux,并且执行者具有相应权限。
这种修改是临时的:restorecon、文件系统重新标记、autorelabel 或某些软件包升级都可能把标签改回策略默认值。需要持久化时应使用 semanage fcontext 定义规则,再执行 restorecon。在非 SELinux 系统上该命令通常不存在或无实际作用。
# 让 Web 服务器读取静态文件
chcon -t httpd_sys_content_t /var/www/html/index.html
# 递归修改目录,并复制参考文件的上下文
chcon -R -t httpd_sys_content_t /var/www/html
chcon --reference=/var/www/html/index.html /var/www/html/new.html
# 验证标签(Z 显示 SELinux 上下文)
ls -lZ /var/www/html/index.html
restorecon -Rv / 后标签恢复原样;持久规则要用 semanage fcontext -a -t ... 加 restorecon。-h 时默认跟随符号链接,改的是目标文件;递归时还要注意 -H、-L、-P 对链接遍历的影响。seinfo -t 确认可用类型。合上页面,先回答,再展开对照。
chcon 修改的标签会永久保留吗?restorecon 后可能恢复,持久化要用 semanage fcontext 加 restorecon。-h。
小程序版
微信扫码,随时查命令