Linux系統中的每一個文件都與多種權限類型相關聯。在這些權限中,我們主要和三類權限打交 道:用戶(user)、用戶組(group)和其他用戶(others)。用戶是文件的所有者;用戶組是指和文件所有者在同一組的其他多個用戶的集合;其 他用戶是除用戶或用戶組之外的任何用戶。
ls -l命令可以列出文件的權限,如:
-rw-rw-r-- 1 lfqy lfqy 529 6月 11 20:21 file-authority.txt
-rw-rw-r-- 1 lfqy lfqy 0 6月 11 19:02 helloworld
drwxrwxr-x 2 lfqy lfqy 4096 6月 11 20:21 try
可以看出,每一行輸出代表一個文件。每行輸出的前10個字符代表文件的權限信息:第一個字符代表文件的類型(-表示普通文件,d表示目錄,c表 示字符設備,b表示塊設備,l表示符號鏈接,s表示套接字,p表示管道),剩下的部分可以劃分成三組(第一組的三個字符對應用戶權限,第二組的三個字符對 應用戶組權限,第三組的三個字符對應其他用戶權限。這9個字符中的每一個字符指明是否設置了某種權限,如果設置了權限,對應位置上就會出現一個字符,否則 就一個'-'表明沒有設置對應的權限)。其中r代表讀權限,w代表寫權限,x代表執行權限,比如第一行中的file-authority.txt文件屬於 用戶lfqy,該用戶對其擁有讀寫權限,而沒有執行權限,和lfqy在同一組的其他用戶也擁有對該文件的讀寫權限,而其他用戶對其只有讀權限。
1、文件的權限
1.1 文件的基本權限
rwx分別對應文件的讀權限、寫權限和可執行權限,然而,對於目錄來說,這三種權限有不同的含義。目錄的讀權限允許讀取目錄中文件和子目錄的列表,目錄的寫權限允許在目錄中創建或刪除文件或目錄,目錄的可執行權限指明是否可以訪問目錄中的文件和子目錄。
1.2 setuid、setgid和sticky bit
實際上,除了最基本的讀、寫和執行權限之外,Linux中還有setuid、setgid和sticky bit等三種權限。下面分別解釋這三種權限。
關於setuid和setgid維基百科上的解釋如下:
setuid and setgid (short for "set user ID upon execution" and "set group ID upon execution", respectively) are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group respectively and to change behaviour in directories. They are often used to allow users on a computer system to run programs with temporarily elevated privileges in order to perform a specific task.
The setuid and setgid flags, when set on a directory, have an entirely different meaning.
Setting the setgid permission on a directory (chmod g+s) causes new files and subdirectories created within it to inherit its group ID, rather than the primary group ID of the user who created the file (the owner ID is never affected, only the group ID). Newly created subdirectories inherit the setgid bit. Thus, this enables a shared workspace for a group without the inconvenience of requiring group members to explicitly change their current group before creating new files or directories. Note that setting the setgid permission on a directory only affects the group ID of new files and subdirectories created after the setgid bit is set, and is not applied to existing entities. Setting the setgid bit on existing subdirectories must be done manually, with a command such as the following:
[root@foo]# find /path/to/directory -type d -exec chmod g+s {} \;
The setuid permission set on a directory is ignored on UNIX and Linux systems. FreeBSD can be configured to interpret it analogously to setgid, namely, to force all files and sub-directories to be owned by the top directory owner.