2.14 文件和目录权限chmod

时间:2022-04-27
本文章向大家介绍2.14 文件和目录权限chmod,主要内容包括文件属性、chmod、chmod例子、首字母缩写更改权限、总结、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

文件属性

[root@localhost ~]# ls -l
总用量 12
-rw-r--r--. 1 root root    0 10月 25 16:06 1.txt
-rw-------. 1 root root 1422 10月 21 00:17 anaconda-ks.cfg

-rw-r--r--. 1 root root 0 10月 25 16:06 1.txt

  • -表示文件的类型,rw-r--r--后面的九位,表示文件的权限
    • r (read)表示可读权限 --数字4表示,r=4
    • w (write)表示可写权限 --数字2表示,w=2
    • x (excute)表示可执行权限 --数字1表示,x=1
    • 总结:rwx=7 rw-=6 --x=1 rw-r--r--=644 rw-r-xr-x=655
  • rw-表示第一段,user所有者的权限
  • r--表示第二段,group所属组的权限
  • r--表示第三段,others其他用户权限
  • 【点.】 有的文件有点,有的没有,意味这个文件受制于SELinux,如果selinux开启,创建的文件或目录在这个位置就会有点
  • 数字1,则表示 相同inode的文件数,与目录下子目录数有关
  • root(第一个),表示文件所属主 ,文件所有者
  • root(第二个),表示文件所属组
  • 0(数字),表示文件大小
  • 25 16:06(时间),表示文件最后一次修改的时间
  • 1.txt,表示文件 (这里可以是目录或文件)

chmod

  • chmod等于change mode
  • chmod命令,用于改变用户对文件或目录的读写执权限
  • chmod -R 表示可以批量更改目录本身以及目录下的子目录和文件的权限
[root@hf-01 ~]# ls -l
总用量 8
-rw-r--r--. 1 root root 924 10月 25 06:49 2.txt
-rw-------. 1 root root 973 8月  21 05:05 anaconda-ks.cfg.1
[root@hf-01 ~]# chmod 700 2.txt     更改2.txt文件权限
[root@hf-01 ~]# ls -l 2.txt
-rwx------. 1 root root 924 10月 25 06:49 2.txt     这里会发现2.txt权限改变了
[root@hf-01 ~]# getenforce  查看防火墙是否关闭
[root@hf-01 ~]# setenforce 0       临时关闭防火墙

若想永久关闭防火墙,则需要更改配置文件
[root@hf-01 ~]# vi /etc/selinux/config     在这个文件下更改

只有关闭了selinux,-rwx------. 最后的这个点才会消失

chmod例子

[root@hf-01 ~]# mkdir hf/   新建目录hf/
[root@hf-01 ~]# ls
2.txt  anaconda-ks.cfg.1  hf
[root@hf-01 ~]# cd hf/
[root@hf-01 hf]# touch 1.txt       新建文件1.txt
[root@hf-01 hf]# ls 
1.txt
[root@hf-01 hf]# ls -l 
总用量 0
-rw-r--r--. 1 root root 0 10月 26 06:56 1.txt
[root@hf-01 hf]# cd
[root@hf-01 ~]# chmod 770 1.txt
chmod: 无法访问"1.txt": 没有那个文件或目录      这是因为1.txt在目录hf/下面
[root@hf-01 ~]# chmod 770 hf/      更改hf/文件夹的权限
[root@hf-01 ~]# ls -l hf/          会发现里面的1.txt权限没有发生变化
总用量 0
-rw-r--r--. 1 root root 0 10月 26 06:56 1.txt
[root@hf-01 ~]# ls -ld hf/         而文件夹的权限则发生了变化
drwxrwx---. 2 root root 18 10月 26 06:56 hf/
[root@hf-01 ~]# chmod -R 661 hf/     在加上了-R选项,文件和目录和子目录批量的更改了权限
[root@hf-01 ~]# ls -l hf/
总用量 0
-rw-rw---x. 1 root root 0 10月 26 06:56 1.txt
[root@hf-01 ~]# ls -ld hf/
drw-rw---x. 2 root root 18 10月 26 06:56 hf/

首字母缩写更改权限

  • u 表示user
  • g 表示group
  • o 表示others
  • a 表示all(全部)
    • 如:u+(-)rwx,g+(-)rwx,o+(-)rwx 如果更改多个属性,中间可用“,”隔开。
    • 又如:a+(-)rwx
[root@hf-01 ~]# chmod u=rwx,g=w,o=r hf/       字母缩写代替更改权限
[root@hf-01 ~]# ls -ld hf/
drwx-w-r--. 2 root root 18 10月 26 06:56 hf/
[root@hf-01 ~]# ls -l hf/
总用量 0
-rw-rw---x. 1 root root 0 10月 26 06:56 1.txt
[root@hf-01 ~]# chmod a+x hf/      所有文件权限都加上x执行权限
[root@hf-01 ~]# ls -ld hf/
drwx-wxr-x. 2 root root 18 10月 26 06:56 hf/
[root@hf-01 ~]# chmod o+w hf/      其他用户组加上w可写的权限
[root@hf-01 ~]# ls -ld hf/
drwx-wxrwx. 2 root root 18 10月 26 06:56 hf/
[root@hf-01 ~]# chmod a-w hf/      所有文件权限减去w可写的权限
[root@hf-01 ~]# ls -ld hf/
dr-x--xr-x. 2 root root 18 10月 26 06:56 hf/

总结

在Linux系统中。目录的默认权限为755,文件的默认权限为644