2016 年 10 月 14 日

Linux Users and Groups

概览

用户一般指使用计算机的人。在本文语境中,该词指用来识别用户的用户名称,既可以是 Mary 或 Bill 这样的真名,也可以是 Dragonlady, Pirate 这样的昵称。关键是,计算机给每个账户分配了特定的名称,而用户则使用这些名称访问计算机。除了人之外,一些系统服务也以有部分限制,又享有部分特权的用户账户身份运行。

由于安全需要,「用户管理」应运而生,以加以明确限制各个用户账户的权限。超级用户 root 于计算机里拥有至高无上的管理权限,所以一般只作管理用。非特权用户则可以用 susudo 程序以临时获得特权。

个体可以拥有多账户,只不过彼此名称当然不同。但有一些用户名称已事先被系统占用,比如 "root".

此外,任意用户可能从属某个「用户组」。此外用户也能够新加入某些已经存在的用户组,以获取该组所拥有的特权。

注意: 新手请务必谨慎地使用这方面的工具,并且要避免对除自己以外的其他已存在用户发生误操作。

权限与属主

摘自 In UNIX Everything is a File (UNIX 中一切皆文件)

集众多灵感及理念之大成,UNIX 操作系统打造出了它的设计、接口、文化甚至革新。重中之重,有一句道理:「一切皆文件」可谓 UNIX 的真谛之一。
根据这一设计原则,必须要有统一的模型,用以管理对大量 I/O 资源的访问:文档、目录、磁盘、CD-ROM、调制解调器、键盘、打印机、显示器和终端等等,甚至也包括了进程、网络之间的通信。而解决之策,就是为所有这些资源提成一个抽象层,UNIX 之父们称之为「文件」。所有文件都通过一致的 API 以提供访问,因此光只用同一套简单的命令,就可以读写磁盘、键盘、文档以及网络设备。

摘自 Extending UNIX File Abstraction for General-Purpose Networking (针对常规的网络应用,扩展出 UNIX 文件抽象层)

UNIX 及兼容系统提供了一个即基本又强悍的抽象层——文件。很多系统服务和设备的应用程序接口,一开始都被设计为文件或文件系统之类的东西。这赋予程序全新的姿态——通过文件抽象层,我们就可以以全新的方式使用众多现成的、且用途单一的小工具。例如 cat 工具,原本只用来读取文件,再将其内容发送到标准输出,但现在它也可以直接访问特殊设备文件(通常在 /dev 目录中),加以读取 I/O 设备。在很多系统上,音频记录和播放也可以通过一令执行:分别是 cat /dev/audio > myfile以及 cat myfile > /dev/audio.

GNU/Linux 系统中的每一个文件都从属一个用户(属主)和一个用户组(属组)。另外,还有三种类型的访问权限:读(read)、写(write)、运行(execute)。我们可以针对文件的属主、属组、而设置相应的访问权限。再次,我们可以通过 ls 命令的长列表格式以查询文件属主、属组和权限:

$ ls /boot/ -l
total 18492
drwxr-xr-x 3 root root    12288 Aug 21 03:27 grub
-rw-r--r-- 1 root root 12487150 Aug 29 18:24 initramfs-linux-fallback.img
-rw-r--r-- 1 root root  2990626 Aug 29 18:23 initramfs-linux.img
-rw-r--r-- 1 root root  3440576 Aug 26 15:17 vmlinuz-linux 

第一列是文件访问权限(例如,文件initramfs-linux.img的权限为-rw-r--r--),第三列和第四列分别是属主和属组(本例中所有文件属主都是root用户,属组都是root组)。

$ ls -l /media/
total 16
drwxrwx--- 1 root vboxsf 16384 Jan 29 11:02 sf_Shared

上述例子中,sf_Shared目录由root用户和vboxsf组所有。使用stat命令也可以查看文件所有权和权限:

属主:

$ stat -c %U /media/sf_Shared/
root

属组:

$ stat -c %G /media/sf_Shared/
vboxsf

访问权限:

$ stat -c %A /media/sf_Shared/
drwxrwx---

访问权限由三组字符组成,分别代表属主、属组、其他人的权限。例如,-rw-r--r--表示属组有读写权限、但无运行权限(rw-),属组用户和其他用户只有读取权限(r--)。又如,drwxrwx---表示文件属主和属组用户有读、写、执行权限(rwx),而禁止其他用户任何访问(---)。第一个字符”d“代表文件类型(目录)。

通过find命令查找属于某个用户或某个组的文件:

# find / -group "用户组"
# find / -user "用户"

文件的属主、属组可以通过chown命令更改。文件的权限可以通过chmod命令修改。

详情参见:man chownman chmodLinux 文件权限

用户管理

使用who命令,可以查看目前已登陆的用户。要查看系统上的用户,以 root 执行 passwd -Sa 输出的数据格式可以参考 passwd(1)

使用useradd命令添加用户:

# useradd -m -g "初始组" -G "附加组" -s "登陆shell" "用户"
  • -m:创建用户主目录/home/[用户名];在自己的主目录内,即使不是root用户也可以读写文件、安装程序等等。
  • -g:设置用户初始组的名称或数字ID;该组必须是存在的;如果没有设置该选项,useradd会根据/etc/login.defs文件中的USERGROUPS_ENAB环境变量进行设置。默认(USERGROUPS_ENAB yes) 会用和用户名相同的名字创建群组,GID 等于 UID.
  • -G:用户要加入的附加组列表;使用逗号分隔多个组,不要添加空格;如果不设置,用户仅仅加入初始组。
  • -s:用户默认登录shell的路径;启动过程结束后,默认启动的登录shell在此处设定;请确保使用的shell已经安装,默认是 Bash
警告: 为了登录,登录 shell 必须位于 /etc/shells 中, 否则 PAMpam_shell 模块会阻止登录请求。不要使用 /usr/bin/bash 替代 /bin/bash, 除非这个路径已经在 /etc/shells中正确配置.
  • 有时候需要禁止某些用户执行登录动作,例如用来执行系统服务的用户。将shell设置成 /usr/bin/nologin 就可以禁止用户登录。(nologin(8)).

添加登录用户

以典型的桌面系统为例,要添加一个名为archie的用户,并使用bash作为登录shell:

# useradd -m -G wheel -s /bin/bash archie

此命令会自动创建 archie 群组,并成为 archie 的默认登录群组。建议每一个用户都设置自己的默认群组,因为umask 默认值是 002, 所以同一个默认群组的用户会有创建文件的写权限。参阅 User Private Groups

要赋予一个群组某个目录的写权限,可以在父目录中设置:

# chmod g+s our_shared_directory

有关useradd的高级用法,参见man页:

$ man useradd

通过下列命令设置用户密码,虽然不是必须的,还是强烈建议设置密码

# passwd [用户名]

If a GID change is required temporarily you can also use the newgrp command to change the user's default GID to another GID at runtime. For example, after executing newgrp groupname files created by the user will be associated with the groupnameGID, without requiring a re-login. To change back to the default GID, execute newgrp without a groupname.

添加系统用户

为进程、守护进程分配不同的系统用户可以更安全的管控目录及文件的访问。下面命令创建一个不创建 home 目录的非登录用户(可以加入 -U 参数创建一个和用户名相同的群组):

# useradd -r -s /usr/bin/nologin username

其它用户管理示例

更改用户登录名:

# usermod -l newname oldname

更改用户主目录:

# usermod -d /my/new/home -m username

-m 选项会自动创建新目录并移动内容。

将用户加入 群组,用逗号分隔:

# usermod -aG 群组 username
警告: 如果不使用 -a 选项,用户会离开没有列在群组的其它群组。

gpasswd 也能实现同样的修改,但是一次只能加入一个组:

# gpasswd --add username group

通过下列命令设置GECOS字段(用户信息,例如用户全名):

# chfn [用户名]

(这样将会以交互式模式启动chfn

此外,可以设置 GECOS comment:

# usermod -c "Comment" username

使用userdel命令删除用户:

# userdel -r [用户名]

-r选项表示一并删除用户主目录和邮件。

Tip: adduserAUR 可以以交互的方式执行 useradd, chfnpasswd,参考 FS#32893.

用户名修改经验

警告: 确保你不是使用你要修改的用户名登录,同时按下(Ctrl+Alt+F1)打开一个新的终端,使用root用户登录,或用其他用户登录后使用su命令登录为root用户。

操作得当的话,在Arch(或其他Linux发行版)中更改用户名是安全的,并且很简单。你可以更改用户所属的组。按照以下步骤进行,可以保留受影响用户的UID和GID,而不会搞乱你已经设置好的文件权限。还有一种方法是手动编辑 /etc/passwd 文件。

  • 如果要使用sudo,请更新文件/etc/sudoers把新的用户(以root登录使用visudo命令)添加进去。
  • 如果修改了~/.bashrc的PATH环境变量,并把新的用户添加进去。。
  • 更改用户名后,我不得不重新安装Thunderbird扩展(Enigmail)。
  • 系统(桌面快捷方式,脚本等)里使用了旧的用户主目录的地方,都需要进行修改。要在脚本中避免这样的问题,可以使用~$HOME变量来表示主目录。

用户信息存储

本地用户信息储存在/etc/passwd文件中。要查看系统上所有用户账户:

$ cat /etc/passwd

一行代表一个用户,格式如下,每行分七个部分,用英文冒号“:”分开:

account:password:UID:GID:GECOS:directory:shell

此处:

  • account:用户名,不能为空,而且要符合标准的*NIX命名规则。
  • password:加密的密码,可以使用一个小写的"x"(不带括号)表示密码保存在/etc/shadow文件里。
  • UID GID:每个用户和组有一个对应的UID和GID(用户ID和组ID)。Arch里面,第一个非root用户的默认UID是1000,后续创建的用户UID也应大于1000,特定用户的GID应该属于指定的首要组,组的ID数值列在/etc/group文件里。
  • GECOS:可选的注释字段,通常记录用户全名
  • directory:用于登录命令设置$HOME环境变量。某些服务的用户主目录设置为"/"是安全的,但不建议普通用户设置为此目录。
  • shell:是用户默认登录的shell,通常是Bash,还可选择其他的命令解释器,默认是"/bin/bash"(不带括号),如果你用的是别的shell,在这里设置其路径,此部分是可选的,可留空。
注意: Arch Linux 使用影子密码。passwd文件对所有人可读,在里面存储密码(无论是否加密过)是很不安全的。在password字段,通常使用一个占位字符(x)代替。加密过的密码储存在/etc/shadow文件,该文件对普通用户限制访问。

示例:

jack:x:1001:100:Jack Smith,some comment here,,:/home/jack:/bin/bash

示例分解说明:用户登录名为jack,密码保存在/etc/shadow,UID为1001,首要组的ID是100 (users组),全名Jack Smith并加了一些注释,主目录是/home/jack,使用Bash作为默认shell。

The pwck command can be used to verify the integrity of the user database. It can sort the user list by GID at the same time, which can be helpful for comparison:

# pwck -s

Note that the Arch Linux defaults of the files are created as .pacnew files by new releases of the filesystem package. Unless Pacman outputs related messages for action, these .pacnew files can, and should, be disregarded/removed. New required default users and groups are added automatically by the packages' install script.

用户组管理

/etc/group文件储存了系统中用户组的信息,详情参见:man group

使用groups命令查看用户所在组的名称:

$ groups [用户名]

若省略用户名,默认显示当前用户所在组。

id命令提供额外的信息,包括用户UID以及相关用户组GID:

$ id [用户名]

查看所有组:

$ cat /etc/group

使用groupadd创建新的组:

# groupadd [组名]

使用gpasswd将用户添加到组:

# gpasswd -a [用户名] [组名]

更改用户所属的组名,不变更GID

# groupmod -n newname oldname

删除用户组:

# groupdel [组名]

将用户从组中移除:

# gpasswd -d [用户名] [组名]

如果用户已登录,必须重新登录使更改生效。

The grpck command can be used to verify the integrity of the system's group files.

Updates to the filesystem package create .pacnew files. Alike the .pacnew files for the #User database, these can be disregarded/removed, because the install script adds any new required groups.

文件列表

警告: 不要手动编辑这些文件。有些工具可以更好的处理锁定、避免数据库错误。
文件 作用
/etc/shadow 保存用户安全信息
/etc/passwd 用户账户信息
/etc/gshadow 保存组账号的安全信息
/etc/group 定义用户所属的组
/etc/sudoers 可以运行 sudo 的用户
/home/* 主目录

群组列表

This section explains the purpose of the essential groups from the core/filesystem package. There are many other groups, which will be created with correct GID when the relevant package is installed. See the main page for the software for details.

Note: A later removal of a package does not remove the automatically created user/group (UID/GID) again. This is intentional because any files created during its usage would otherwise be left orphaned as a potential security risk.

用户组

影响文件 作用
adm 类似 wheel 的管理器群组.
ftp /srv/ftp/ 访问 FTP 服务器.
games /var/games 访问一些游戏。
log 访问 syslog-ng 创建的 /var/log/ 日志文件.
http /srv/http/ 访问 HTTP 服务器文件.
rfkill 不再使用! 控制无线设备的电源 (可能被 rfkill 使用).
sys Right to administer printers in CUPS.
systemd-journal /var/log/journal/* 以只读方式访问系统日志,和 admwheel 不同 [1]. 不在此组中的用户仅能访问自己生成的信息。
users 标准用户组.
uucp /dev/ttyS[0-9]+, /dev/tts/[0-9]+, /dev/ttyUSB[0-9]+, /dev/ttyACM[0-9]+ 串口和 USB 设备,例如猫、手柄 RS-232/串口。
wheel 管理组,通常用于 sudo 和 su 命令权限。systemd 会允许非 root 的 wheel 组用户启动服务。[2]

系统组

下列组系统使用,一般不被 Arch 用户使用:

影响文件 作用
avahi
clamav /var/lib/clamav/*, /var/log/clamav/* Clam AntiVirus 使用.
dbus /var/run/dbus/*
kmem /dev/port, /dev/mem, /dev/kmem
locate /usr/bin/locate, /var/lib/locate, /var/lib/mlocate, /var/lib/slocate See Core utilities#locate.
lp /dev/lp[0-9]*, /dev/parport[0-9]*, /etc/cups, /var/log/cups, /var/cache/cups,/var/spool/cups Access to parallel port devices (printers and others) and read-only access to CUPS files. If you run a non-printer parallel port device, see FS#50009for implied problems.
mail /usr/bin/mail
mpd /var/lib/mpd/*, /var/log/mpd/*, /var/run/mpd/*, 可选的音乐目录 MPD 组.
nobody 无权限的组。
ntp /var/lib/ntp/* NTPd 组.
root /* 完全的系统管理和控制 (root, admin)
smmsp sendmail 群组.
tty /dev/tty, /dev/vcc, /dev/vc, /dev/ptmx 访问 /dev/ACMx
utmp /run/utmp, /var/log/btmp, /var/log/wtmp
vboxsf 虚拟系统的共享目录 VirtualBox使用.

systemd 之前的群组

Before arch migrated to systemd, users had to be manually added to these groups in order to be able to access the corresponding devices. This way has been deprecated in favour of udev marking the devices with a uaccess tag and logind assigning the permissions to users dynamically via ACLs according to which session is currently active. Note that the session must not be broken for this to work (see General troubleshooting#Session permissions to check it).

There are some notable exceptions which require adding a user to some of these groups: for example if you want to allow users to access the device even when they are not logged in. However, note that adding users to the groups can even cause some functionality to break (for example, the audio group will break fast user switching and allows applications to block software mixing).

如下组是 systemd 之前使用,目前已经没有任何作用,使用后还可能对功能有影响:

作用
audio /dev/audio, /dev/snd/*, /dev/rtc0 直接访问声音硬件(ALSAOSS).
camera 访问 Digital Cameras.
disk /dev/sda[1-9], /dev/sdb[1-9] 直接访问不受 optical, floppystorage 组控制的块设备. 除非有特殊需要, 否则不建议将一般用户添加至该组.
floppy /dev/fd[0-9] 访问软盘驱动器。
lp /etc/cups, /var/log/cups, /var/cache/cups, /var/spool/cups 访问打印设备,管理打印任务。
network 改变网络设置的权限,比如使用 NetworkManager 的权限.
optical /dev/sr[0-9], /dev/sg[0-9] 访问光学设备,比如CD,DVD。
power 使用 Pm-utils (挂起、休眠...) 和电源管理控制。
scanner /var/lock/sane 访问扫描仪硬件。
storage 访问可移动储存器,例如 USB 硬盘、flash 存储器、MP3 播放器等;用户可以通过 D-Bus 挂载设备。
sys 管理 CUPS 中的打印机.
video /dev/fb/0, /dev/misc/agpgart 访问视频捕获和硬件加速设备。例如framebuffer (X 不属于这个组也能使用).

不再使用的组

Group Affected files Purpose
bin none Historical
daemon
lock
mem
network Unused by default. Can be used e.g. for granting access to NetworkManager (see NetworkManager#Set up PolicyKit permissions).
power
uuidd

If you are new to Linux/Unix, then the concept of permissions may be confusing. This guide will provide you with an explanation of what permissions are, how they work, and how to manage them. A number of examples will be provided to illustrate how to set and change permissions for both users and groups.

What are User and Group Permissions?

Linux/Unix operating systems have the ability to multitask in a manner similar to other operating systems. However, Linux’s major difference from other operating systems is its ability to have multiple users. Linux was designed to allow more than one user to have access to the system at the same time. In order for this multiuser design to work properly, there needs to be a method to protect users from each other. This is where permissions come in to play.

Read, Write & Execute Permissions

Permissions are the “rights” to act on a file or directory. The basic rights are read, write, and execute.

  • Read - a readable permission allows the contents of the file to be viewed. A read permission on a directory allows you to list the contents of a directory.
  • Write - a write permission on a file allows you to modify the contents of that file. For a directory, the write permission allows you to edit the contents of a directory (e.g. add/delete files).
  • Execute - for a file, the executable permission allows you to run the file and execute a program or script. For a directory, the execute permission allows you to change to a different directory and make it your current working directory. Users usually have a default group, but they may belong to several additional groups.

Viewing File Permissions

To view the permissions on a file or directory, issue the command ls -l <directory/file>. Remember to replace the information in the < > with the actual file or directory name. Below is sample output for the ls command:

1
-rw-r--r-- 1 root root 1031 Nov 18 09:22 /etc/passwd

The first ten characters show the access permissions. The first dash (-) indicates the type of file (d for directory, s for special file, and - for a regular file). The next three characters (rw-) define the owner’s permission to the file. In this example, the file owner has read and write permissions only. The next three characters (r–) are the permissions for the members of the same group as the file owner (which in this example is read only). The last three characters (r–) show the permissions for all other users and in this example it is read only.

Working with Users, Groups, and Directories

The following sections will go over the commands needed to create, delete, and modify user accounts. Groups will be covered, as well as commands for creating and deleting directories. You will be provided with the commands and descriptions needed for working with users, groups, and directories.

Creating and Deleting User Accounts

To create a new standard user, use the useradd command. The syntax is as follows:

1
useradd 

The useradd command utilizes a variety of variables, some of which are shown in the table below:

Option Description Example
-d home_dir will be used as the value for the user’s login directory useradd -d /home/<user\'s home>
-e the date when the account will expire user add ** -e
-f the number of days before the account expires useradd -f
-s sets the default shell type useradd -s /bin/

You will need to set a password for the new user by using the passwd command. Note, you will need root privileges to change a user password. The syntax is as follows:

1
passwd 

The user will be able to change their password at any time using the passwd command with the syntax. Below is an example:

1
2
3
4
5
6
$ passwd
Changing password for lmartin.
(current) UNIX password:
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully

There is another way of creating user accounts that might be easier for first-time administrators. However, you may need to install a new package. The installation command for Debian/Ubuntu is as follows:

1
apt-get install adduser

The adduser command automatically creates a home directory and sets the default group, shell, etc. To create a new standard user with the adduser command the syntax is as follows:

1
adduser 

Once you enter the command you will receive a series of prompts; most of this information is optional. However, you should include at least the user’s name (for this example the user name is cjones) and of course a password.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
root@localhost:~# adduser cjones
  Adding user `cjones\' ...
  Adding new group `cjones\' (1001) ...
  Adding new user `cjones\' (1001) with group `cjones\' ...
  Creating home directory `/home/cjones\' ...
  Copying files from `/etc/skel\' ...
  Enter new UNIX password:
  Retype new UNIX password:
  passwd: password updated successfully
  Changing the user information for cjones
  Enter the new value, or press ENTER for the default
      Full Name []: Chuck Jones
      Room Number []: 213
      Work Phone []: 856-555-1212
      Home Phone []:
      Other []:
  Is the information correct? [Y/n] Y

It is important to note that security should always be taken very seriously. Therefore, it is strongly recommended to use unique passwords for each account. Never share or give your password to other users.

To remove a user account, enter the following command:

1
userdel 

Issuing the command above will only delete the user’s account. Their files and home directory will not be deleted.

To remove the user, their home folder, and their files, use this command:

1
userdel -r 

Understanding Sudo

Root is the super user and has the ability to do anything on a system. Therefore, in order to have protection against potential damage sudo is used in place of root. Sudo allows users and groups access to commands they normally would not be able to use. Sudo will allow a user to have administration privileges without logging in as root. A sample of the sudo command is as follows:

1
sudo apt-get install 

Before using sudo, it may need to be installed if it is not part of your distribution. The command for Debian is as follows:

1
apt-get install sudo

For CentOS, the command is as follows:

1
yum install sudo

In order to provide a user with sudo ability, their name will need to be added to the sudoers file. This file is very important and should not be edited directly with a text editor. If the sudoers file is edited incorrectly it could result in preventing access to the system.

Therefore the visudo command should be used to edit the sudoers file. At a command line, log into your system as root and enter the command visudo.

Below is the portion of the sudoers file that shows the users with sudo access.

1
2
3
4
5
# User privilege specification
root    ALL=(ALL:ALL) ALL
cjones  ALL=(ALL:ALL) ALL
kbrown  ALL=(ALL:ALL) ALL
lmartin ALL=(ALL:ALL) ALL

After you have given your user account sudo privileges, save the sudoers file and log out as root. Now log in as your user and test the privileges as your user with sudo access. When a new user needs sudo access, you will now be able to edit the sudoers file with your own login using the following command:

1
sudo visudo

Working with Groups

Linux uses groups as a way to organize users. Groups organize collections of accounts, primarily as a security measure. Control of group membership is administered through the /etc/group file, which shows a list of groups and its members. Every user has a default or primary group. When a user logs in, the group membership is set for their primary group. This means that when a user launches a program or creates a file, both the file and the running program will be associated with the user’s current group membership. A user may access other files in other groups, as long as they are also a member of that group and the access permissions are set. To run programs or create a file in a different group, the user must run the newgrp command to switch their current group. A sample of the newgrp command is as follows:

1
$ newgrp 

If the user entering the above-referenced command is a member of the marketing group in the/etc/group file, then the current group membership will change. It is important to note that any files created will now be associated with the marketing group rather than the user’s primary group. Users may also change their group by using the chgrp command. The syntax for the chgrp command is as follows:

1
$ chgrp 

Creating and Removing Directories

To make a directory use the command:

1
mkdir 

To make a directory and set the permissions at the same time, use the following option and syntax:

1
mkdir -m a=rwx 

The -m option is short for mode, and a=rwx means that all users have read, write, and execute permissions on the directory. To see a complete list of all options for the mkdir command enterman mkdir at a command prompt.

To remove a file, use the following:

1
rm 

To remove a directory:

1
rm -r 

It is important to note that if you remove a directory all the files inside will be deleted as well.

Changing Directory and File Permissions

To view file permissions and ownership on files and directories, use the ls -al command. The aoption is to show hidden files or all files, and the l option is for the long listing. The output will be similar to the following:

1
2
3
drwxr-xr-x 2 user user 4096 Jan  9 10:11 documents
-rw-r--r-- 1 user user  675 Jan  7 12:05 .profile
drwxr-xr-x 4 user user 4096 Jan  7 14:55 public

The first column with the ten letters and dashes shows the permissions of the file or directory. The second column (with the single number) indicates the number of files or directories contained in the directory. The next column indicates the owner, followed by the group name, the size, date, and time of last access, and finally the name of the file . For example, using the first line from the output above, the details are as follows:

1
2
3
4
5
6
7
``drwxr-xr-x`` are the permissions
``2`` is the number of files or directories
``user`` is the owner
``user`` is the group
``4096`` is the size
``Jan  9 10:11`` is the date/time of last access
``documents`` is the directory

Since a directory itself is a file, any directory will always show 4096 as it’s size. This does not reflect the size of the contents of the directory.

Chmod Command

The command chmod is short for change mode. Chmod is used to change permissions on files and directories. The command chmod may be used with either letters or numbers (also known as octal) to set the permissions. The letters used with chmod are in the table below:

Letter Permission
r Read
w Write
x Execute
X Execute (only if file is a directory)
s Set user or group ID on execution
t Save program text on swap device
u Current permissions the file has for owner
g Current permissions the file has for users in the same group
o Current permissions the file has for others not in the group

It is important to remember that the first character of the first column of a file listing denotes whether it is a directory or a file. The other nine characters are the permissions for the file/directory. The first three characters are for the user, the next three are for the group, and the last three are for others. The example drwxrw-r– is broken down as follows:

d is a directory

rwx the user has read, write, and execute permissions

rw- the group has read and write permissions

r– all others have read only permissions

Note that the dash (-) denotes permissions are removed. Therefore, with the “all others” group, r– translates to read permission only, the write and execute permissions were removed.

Conversely, the plus sign ( ) is equivalent to granting permissions: chmod u r,g x

The example above translates as follows:

1
2
3
4
u is for user
r is for read
g is for group
x is for execute

In other words, the user was given read permission and the group was given execute permission for the file. Note, when setting multiple permissions for a set, a comma is required between sets.

Chmod Octal Format

To use the octal format, you have to calculate the permissions for each portion of the file or directory. The first ten characters mentioned above will correspond to a four digit numbers in octal. The execute permission is equal to the number one (1), the write permission is equal to the number two (2), and the read permission is equal to the number four (4). Therefore, when you use the octal format, you will need to calculate a number between 0 and 7 for each portion of the permission. A table has been provided below for clarification.

北京网站建设资讯 - Linux Users and Groups - (1)

Although octal format may seem difficult to understand, it is easy to use once you get the gist of it. However, setting permissions with r, w, and x may be easier. Below are examples of how to use both letters and octal format to set permissions on a file or directory.

Sample syntax: chmod <file/directory name>

Letter format: chmod go-rwx Work (Deny rwx permission for the group and others)

The output of ls -al after the chmod command above would looks as follows:

1
dr-------- 2 user user 4096 Dec 17 14:38 Work

Octal format: chmod 444 Work

The output of ls -al after the chmod command above would look as follows:

1
dr--r--r-- 2 user user 4096 Dec 17 14:38 Work

An octal table showing the numeric equivalent for permissions is provided below.

北京网站建设资讯 - Linux Users and Groups - (2)

Additional File Permissions

In addition to the most common read/write/execute file permissions, there are some additional modes that you might find useful, specifically the t mode (sticky bit) and the s mode (setuid bit). These functions describe the behavior of files and executables in multi-user situations.

When set on a file or directory, the sticky bit, or t mode, means that only the owner (or root) can delete the file, regardless of which users have write access to this file/directory by way of group membership or ownership. This is useful when a file or directory is owned by a group through which a number of users share write access to a given set of files.

To set the sticky bit on a file named /root/sticky.txt, issue the following command:

1
chmod  t /root/sticky.txt

To remove the sticky bit from a file, use the chmod -t command. Note, to change the sticky bit, you need to be either root or the file owner. The root user will be able to delete files regardless of the status of the sticky bit.

The setuid bit, or s, when set on files allows users with permissions to execute a given file the ability to run that file with the permissions of file owner. For instance, if the file work was owned by the root user and the marketing group, members of the marketing group could run the workprogram as if they were the root user. This may pose potential security risks in some cases and executables should be properly evaluated before receiving the s flag. To set the s bit on a file named /usr/bin/work, issue the following command:

1
chmod g s /usr/bin/work

In contrast to the s mode for the ownership of a file, the effect of the s mode on a directory is somewhat different. Files created in s directories receive the ownership of that directory’s user and group, rather than the ownership of the user that created the file and their default group. To set the setguid (group id) option on a directory, use the following command:

1
chmod g s /var/doc-store/

To set the setuid (user id) for a directory named /var/doc-store, issue the following command:

1
chmod o s /var/doc-store/

Changing File Ownership

By default, all files are “owned” by the user who creates them and by that user’s default group. To change the ownership of a file, use the chown command in the chown user:group /path/to/fileformat. In the following example, the ownership of the “list.html” file will be changed to the “cjones” user in the “marketing” group:

1
chown cjones:marketing list.html

To change the ownership of a directory and all the files contained inside, use the recursive option with the -R flag. In the following example, change the ownership of /srv/smb/leadership/ to the “cjones” user in the “marketing” group:

1
chown -R cjones:marketing /srv/smb/leadership/

Leveraging Users and Groups

In many cases, user permissions are used to provide your system with greater security without any direct interaction. Many operating systems create specific system user accounts for different packages during the installation process.

The best practice is to give each user their own login to your system. This protects each user’s files from all other users. Furthermore, using specific accounts for users allows more accurate system logging, particularly when combined with tools like sudo. We recommend avoiding situations where more than one individual knows the password for a user account for maximum security.

In contrast, groups are useful for allowing multiple independent user accounts to collaborate and share files. If you create groups on a machine for common tasks on a per-task basis (e.g. web editors, contributors, content submitters, support) and add relevant users to the relevant groups, these users can all edit and run the same set of files without sharing these files with the world. Use of the chown command with file permissions of 770 and 740 would help accomplish this goal.