명령어/Linux

[RHEL] chcon 파일 컨텍스트 임시 변경

jykim23 2026. 7. 18. 19:02
반응형

부제: 파일 하나의 SELinux 라벨을 그 자리에서 바꾼다

chcon -t httpd_sys_content_t /srv/demo.txt   # 타입만 변경
chcon --reference=/srv/a.txt /srv/b.txt      # 다른 파일 라벨 복사
unconfined_u:object_r:var_t:s0 /srv/demo.txt
unconfined_u:object_r:httpd_sys_content_t:s0 /srv/demo.txt

chcon(change context)은 파일이나 디렉터리의 컨텍스트를 직접 지정한다. -u, -r, -t로 user·role·type을 각각 바꾸고, --reference로 기준 파일의 라벨을 그대로 복사한다. 웹 루트가 아닌 곳에 둔 콘텐츠를 httpd가 읽게 하려고 httpd_sys_content_t를 붙이는 식으로 급히 쓴다.

주의할 점은 chcon 변경이 파일시스템에만 임시로 남는다는 것이다. 나중에 restorecon이나 정책 재적용이 돌면 정책상 기본값으로 되돌아간다. 영구적으로 바꾸려면 semanage fcontext로 정책에 규칙을 등록해야 한다. 데비안 AppArmor는 파일 라벨을 쓰지 않으므로 대응 명령이 없다.

이렇게도 쓴다

타입만 바꾸고 결과를 ls -Z로 바로 확인한다(조합용).

chcon -t httpd_sys_content_t /srv/demo.txt && ls -Z /srv/demo.txt

 

디렉터리 이하를 재귀로 한꺼번에 바꾼다.

chcon -R -t httpd_sys_content_t /srv/site

 

기준 파일의 라벨을 다른 파일에 그대로 복사한다.

chcon --reference=/srv/a.txt /srv/b.txt

 

전체 컨텍스트 문자열을 통째로 지정한다.

chcon system_u:object_r:httpd_sys_content_t:s0 /srv/demo.txt

 

matchpathcon으로 정답 라벨을 확인한 뒤 그 타입으로 맞춘다(조합용).

chcon -t "$(matchpathcon /var/www/html | awk -F: '{print $3}')" /srv/demo.txt
반응형