在 CentOS 上排查 SELinux context(安全上下文) 问题,通常可以按下面步骤来做。我按「从现象到定位再到修复」的思路说明。
很多问题不是 context 本身,而是 SELinux 被启用。
getenforce
# Enforcing / Permissive / Disabled
查看整体状态:
sestatus
如果不确定是不是 SELinux 导致:
setenforce 0 # 临时改为 Permissive
再试一次操作。
如果没问题了 → 基本就是 SELinux / context 问题。
ls -Z /var/www/html/index.html
ps -Z
示例输出:
unconfined_u:object_r:default_t:s0
ps -eZ | grep httpd
semanage port -l | grep http
比如 Nginx/Apache 报 Permission denied
正确 context 通常是:
httpd_sys_content_t
修复:
semanage fcontext -a -t httpd_sys_content_t "/data/web(/.*)?"
restorecon -Rv /data/web
例如 Nginx 用 8080 / 8443
查看:
semanage port -l | grep http_port_t
添加:
semanage port -a -t http_port_t -p tcp 8080
mv file /var/www # context 不会变
cp file /var/www # 通常会继承
修复:
restorecon -Rv /var/www
ausearch -m AVC -ts recent
或
grep AVC /var/log/audit/audit.log
sealert -a /var/log/audit/audit.log
它会直接告诉你:
# 修改默认 context 规则(永久)
semanage fcontext -a -t 类型 "/路径(/.*)?"
# 立即生效
restorecon -Rv /路径
# 临时改(重启失效)
chcon -t httpd_sys_content_t /path
setenforce 0
或
# 给某布尔值开
getsebool -a | grep http
setsebool -P httpd_can_network_connect on
你可以告诉我:
audit.log 片段我可以直接帮你写 精确修复命令。