在CentOS中,文件/目錄的權限分為三類用戶和三種操作權限:
通過ls -l命令可查看權限詳情(如-rwxr-xr--),其中第1位為文件類型(-為普通文件、d為目錄),后9位分為3組(所有者、所屬組、其他用戶)。
ls -lls -l /path/to/file_or_directory
輸出示例:-rw-r--r-- 1 user group 4096 Jan 1 12:34 file.txt
解讀:所有者(user)有讀寫權限(rw-),所屬組(group)和其他用戶有讀權限(r–)。
chmod語法:chmod [who][operator][permission] file
who:u(所有者)、g(所屬組)、o(其他用戶)、a(所有用戶)。operator:+(添加權限)、-(移除權限)、=(設置權限)。permission:r(讀)、w(寫)、x(執行)。示例:
chmod u+x script.shchmod go-w file.txtchmod a=rwx,u-w file.txt。語法:chmod xyz file(x、y、z為0-7數字,對應權限之和)
常見組合:
755:所有者(7=rwx)、組和其他用戶(5=r-x),適用于目錄(如/var/www/html)。644:所有者(6=rw-)、組和其他用戶(4=r–),適用于普通文件(如config.conf)。777:所有用戶均有讀寫執行權限(慎用,僅測試環境用)。chown/chgrp語法:chown [新所有者][:新組] file
示例:
file.txt所有者改為admin:chown admin file.txtchown admin:developers file.txtchown -R admin:developers /project。語法:chgrp [新組] file
示例:
file.txt所屬組改為developers:chgrp developers file.txtchgrp -R developers /project。作用:文件執行時,進程繼承所有者權限(如passwd命令)。
設置:chmod u+s file(如chmod 4755 /usr/bin/passwd)。
作用:目錄下新建文件時,自動繼承目錄的所屬組(便于團隊協作)。
設置:chmod g+s directory(如chmod 2770 /project/src)。
作用:目錄下文件只能由所有者、目錄所有者或root刪除(如/tmp目錄)。
設置:chmod +t directory(如chmod 1777 /tmp)。
使用-R選項修改目錄及其所有子文件/子目錄的權限(謹慎使用777):
chmod -R 755 /path/to/directory # 遞歸設置目錄權限
chown -R user:group /path/to/directory # 遞歸修改所有者/組
umaskumask定義文件/目錄創建時的默認權限(取反后減去基礎權限):
666 - umask(如umask 022→644)。777 - umask(如umask 022→755)。查看當前umask:umask
設置umask(臨時):umask 027(所有者全權限,組讀權限,其他用戶無權限)。
當需要為特定用戶/組設置權限時,使用setfacl命令(需安裝acl包:yum install acl)。
示例:
devuser添加目錄讀寫權限:setfacl -m u:devuser:rwx /projectdevelopers添加目錄執行權限:setfacl -m g:developers:x /projectgetfacl /projectsetfacl -R -m u:devuser:rwx /project。sudo臨時提權(需加入wheel組):sudo command # 如sudo apt-get update
wheel組:sudo usermod -aG wheel username。SELinux是CentOS的安全模塊,可能限制權限(如無法訪問/var/www/html)。
sestatus(Enforcing為開啟)。sudo setenforce 0(重啟后恢復)。/etc/selinux/config,將SELINUX=enforcing改為SELINUX=disabled(需重啟)。chmod 777(會暴露敏感文件)。ls -l)和SELinux狀態(sestatus)。