在 CentOS(尤其是 CentOS 7/8 以及使用 SELinux 的场景)中,“Context 文件”通常指的是 SELinux 的上下文(Security Context)相关文件,常见有两类:
.fc 文件)semanage fcontext 生成)下面分情况说明如何“生成”。
ls -Z /path/to/file
示例:
ls -Z /var/www/html/index.html
semanage fcontext 生成 Context 规则(推荐)这是生成 Context 配置的标准方式。
semanage fcontext -a -t httpd_sys_content_t "/data/web(/.*)?"
含义:
-a:添加-t:指定类型/data/web(/.*)?:匹配该目录及子目录restorecon -Rv /data/web
✅ 这是 CentOS 中最常见、最标准的“生成 Context 文件”的方式。
semanage fcontext 的规则最终存储在:
/etc/selinux/targeted/contexts/files/file_contexts.local
你可以直接查看:
cat /etc/selinux/targeted/contexts/files/file_contexts.local
.fc 文件)如果你是 编写自定义 SELinux 策略模块,需要生成 .fc 文件。
.fc 文件# myapp.fc
/usr/local/bin/myapp -- gen_context(system_u:object_r:myapp_exec_t,s0)
/var/lib/myapp(/.*)? gen_context(system_u:object_r:myapp_data_t,s0)
.te 策略文件# myapp.te
policy_module(myapp, 1.0)
type myapp_exec_t;
type myapp_data_t;
files_type(myapp_data_t)
make -f /usr/share/selinux/devel/Makefile
semodule -i myapp.pp
⚠️ 重启或 restorecon 后可能失效
chcon -t httpd_sys_content_t /data/web/index.html
| 场景 | Context 类型 |
|---|---|
| Web 目录 | httpd_sys_content_t |
| Nginx 日志 | httpd_log_t |
| SSH 密钥 | ssh_home_t |
| 可执行程序 | bin_t |
| 数据库数据 | mysqld_db_t |
| 需求 | 方法 |
|---|---|
| 给目录/文件设置 SELinux 上下文 | semanage fcontext + restorecon |
| 查看 Context | ls -Z |
| 编写 SELinux 模块 | .fc + .te + make |
| 临时修改 | chcon |
如果你能具体说明:
我可以给你更精确的示例。