Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

Linux文件权限 #135

Open Qingquan-Li opened 4 years ago

Qingquan-Li commented 4 years ago

参考:


一、查看文件权限

以下命令实例,是在虚拟机中的 Ubuntu 系统中执行的。

# 查看当前文件夹及上级文件权限(虚拟机中的Ubuntu实例)
~/Desktop$ ls -la
total 16
drwxr-xr-x  2 fatli fatli 4096 Apr 28 23:17 .
drwxr-xr-x 26 fatli fatli 4096 Apr 28 18:32 ..
-rwxrwxrwx  1 fatli fatli 2909 Apr 28 16:51 mysqlbackup.sh
-rw-r--r--  1 fatli fatli   37 Apr 28 23:16 test.sh
# 查看指定文件的权限(虚拟机中的Ubuntu实例)
~/Desktop $ ls -l test.sh
-rw-r--r-- 1 fatli fatli 37 Apr 28 23:16 test.sh
# 权限为(4+2)44
# 此时 test.sh 脚本文件只有`r`读 和 `w`写 的权限,没有 `x`执行 的权限:
~/Desktop$ ~/Desktop/test.sh
bash: /home/fatli/Desktop/test.sh: Permission denied
# 更改 test.sh 脚本文件权限,让拥有者owner(这里是fatli)拥有 `x`执行 的权限:
~/Desktop$ chmod 744 test.sh
~/Desktop$ ls -l test.sh
-rwxr--r-- 1 fatli fatli 37 Apr 28 23:16 test.sh
# 或者,更改 test.sh 脚本文件权限,让 owner, group, others 都拥有 `x`执行 的权限:
~/Desktop$ chmod +x test.sh
~/Desktop$ ls -l test.sh
-rwxr-xr-x 1 fatli fatli 25 Apr 29 00:02 test.sh

~/Desktop$ test.sh
test.sh: command not found
# 成功执行并打印出 test.sh 文件中的内容:`echo "this is a sh test"`
~/Desktop$ ~/Desktop/test.sh
this is a sh test
权限计算公式:
每种身份 (owner/group/others) 各自的三个权限 (r/w/x) 读/写/执行,分数是需要累加的,例如上面的 test.sh 文件权限为:`-rwxr--r--` 分数则是:
owner  = rwx  = 4+2+1 = 7
group  = r--  = 4+0+0 = 4
others = r--  = 4+0+0 = 4
其中,打头的第一个字母代表文件的类型。例如这里是 `-` 代表文件;如果此处为 `d` (例如上面的 `~/Desktop$ ls -la` )则代表目录,即文件夹。


二、文件权限应用场景

例如,当前使用 $ ssh username@server 登录远程 Ubuntu 主机 ,如果当前文件权限属于 root 用户,当前登录的 username 用户则无法进行读写等操作。 如需进行读写等操作,需要切换到 root 用户:

$ sudo passwd root  # 设置root密码:root密码可以动态修改,忘记密码可以重设密码后再进入root
$ su    # 切换到root:原来的文件路径($ pwd查看)和环境(例如Python conda环境)都没有改变
$ su -  # 切换到root:用户权限、文件路径和环境一起切换成root
$ exit  # 退出root

或进入权限属于 username 用户的文件进行读写操作,例如执行 $ cd 进入 ~ (以 Ubuntu 为例,此时 ~ 等价 /home/username )。