Linux 文件权限

相对于 Windows,Linux 的文件权限有些复杂。本文将会对文件权限进行一些简单的说明。

Warning:

root 账号可无视权限操作,拥有全部文件的所有权限。

常用命令

在操作文件权限前应先知道当前文件、文件夹是什么权限:

1
2
3
4
5
6
7
[root@localhost nginx]# ls -al /etc/
总用量 1384
drwxr-xr-x. 102 root root 8192 5月 24 09:15 .
dr-xr-xr-x. 18 root root 4096 8月 9 2017 ..
-rw-r--r--. 1 root root 44 11月 13 2017 adjtime
lrwxrwxrwx. 1 root root 6 7月 16 2015 zsoelim -> soelim
drwxr-xr-x. 2 root root 4096 4月 18 2017 alternatives

解析如下:

文件类型 所有者权限 组用户权限 其他用户权限 链接数 用户名 组名 文件大小(字节) 最后修改时间 文件名
d rwx r-x r-x . 102 root root 8192 5月 24 09:15 .
d r-x r-x r-x . 18 root root 4096 8月 9 2017 ..
- rw- r– r– . 1 root root 44 11月 13 2017 adjtime
l rwx rwx rwx . 1 root root 6 7月 16 2015 zsoelim -> soelim
d rwx r-x r-x . 2 root root 4096 4月 18 2017 alternatives
  • 文件类型:- 文件、d 文件夹、l 软链接
  • rwx:r=4读、w=2写、x=1执行
  • 链接数:文件链接数 / 子目录数

chmod

符号模式:

  • 用户 u
  • 组用户 g
  • 其他用户 o
  • 全部权限 a = ugo
  • 添加权限 +
  • 去除权限 -
  • 覆盖权限 =
  • 读 r
  • 写 w
  • 执行 x

数字权限值解析:

  1. 执行
  2. 执行 + 写 = 1 + 2
  3. 执行 + 读 = 1 + 4
  4. 写 + 读 = 2 + 4
  5. 执行 + 写 + 读 = 1 + 2 + 4

Warning:

文件夹要有可执行,要不然 cd 不进去;无写权限无法重命名和删除。不是操作的文件或文件夹的所有者账户,就需要有其他用户权限有执行权限才可以进行操作。

1
2
3
4
5
6
7
8
9
chmod 755 file
chmod 755 dir
chmod 755 -R dir

chmod u+r file
chmod ug+r file
chmod a+rwx file
chmod a-w file
chmod a=rw file

chown

修改文件所有者、所在分组,Linux 上运行软件为了安全,都会创建个单独的分组给软件。分组中你想做什么操作都行,但其他所有者和分组,没权限的操作根本无法执行。

Warning:

只有系统管理者才可以修改文件分组,除 root 账户外,需要用户有 sudo 命令使用权限。查看 Linux sudo 命令 了解更多。

1
2
3
4
5
6
7
# 普通用户
sudo chown newuser:newgroup file
sudo chown newuser:newgroup -R dir

# root
chown newuser:newgroup file
chown newuser:newgroup -R dir