How to use the sudoers file in Linux?

The sudoers file is located in /etc/sudoers and is used to configure permissions for the sudo command.

There are two editing methods supported by the sudoers file.

  1. Edit the sudoers file using the visudo command.
sudo visudo

Visudo performs a syntax check before editing the sudoers file, giving a warning for any syntax errors. This is the recommended way to edit the file.

  1. Edit the sudoers file directly using a text editor.
sudo nano /etc/sudoers

You need to be extremely careful when editing the sudoers file using a text editor, as syntax errors can prevent the sudo command from functioning properly.

The following can be configured in the sudoers file:

  1. User permission control:
<用户或用户组> <主机=(执行命令的用户)> <运行命令的命令>

For example, granting the user Bob permission to run all commands as root on all hosts.

bob ALL=(root) ALL
  1. Command alias:
Cmnd_Alias <别名> = <命令1>, <命令2>, ...

For example, create an alias named MYCOMMANDS, which includes /bin/ls and /bin/cat.

Cmnd_Alias MYCOMMANDS = /bin/ls, /bin/cat

Then you can use the alias for permission control.

bob ALL=(root) MYCOMMANDS
  1. Group permissions control:
%<用户组> <主机=(执行命令的用户)> <运行命令的命令>

For example, granting the user group admins the permission to run all commands as root on all hosts.

%admins ALL=(root) ALL
  1. Other options are also supported in the sudoers file, such as setting the default PATH and disabling the root user. Please refer to the comments in the sudoers file or the sudoers manual page (man sudoers) for more information.

After saving the sudoers file, new configuration permissions must be either re-logged in or applied using the following command to take effect:

sudo -k

You can now execute the command using the new configuration by using the sudo command again.

bannerAds