From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Sudo and the translation is 39% complete.
Outdated translations are marked like this.
Other languages:

sudo 命令提供了一个简单和安全的方式来配置权限提升——比如让普通用户以 root 或其他用户身份运行某些(甚至全部)命令,而不需要提供密码。

为了允许某些用户在系统上执行某些管理步骤而不授予他们全部 root 权限,使用 sudo 是最好的选择。使用 sudo 可以控制谁可以做什么。本指南简要介绍了这个强大的工具。

此文章仅是一个快速介绍,app-admin/sudo包远比这里描述的要强大。它还有其他特殊功能,譬如以其他用户身份编辑文件 (sudoedit),从脚本内部运行(这样它就可以在后台运行,从标准输入中读取密码而不是从键盘)……等等。

更多信息请阅读 sudosudoers手册。


sudo is not part of the system set, so it must be installed manually, if it is needed.
The su command should always be available, in case sudo is not installed.

USE 标记

USE flags for app-admin/sudo Allows users or groups to run commands as other users

gcrypt Use message digest functions from dev-libs/libgcrypt instead of sudo's
ldap Add LDAP support (Lightweight Directory Access Protocol)
nls Add Native Language Support (using gettext - GNU locale utilities)
offensive Let sudo print insults when the user types the wrong password
pam Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip
sasl Add support for the Simple Authentication and Security Layer
secure-path Replace PATH variable with compile time secure paths
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
sendmail Allow sudo to send emails with sendmail
skey Enable S/Key (Single use password) authentication support
ssl Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security)
sssd Add System Security Services Daemon support
verify-sig Verify upstream signatures on distfiles


root #emerge --ask app-admin/sudo



One additional advantage of sudo is that it can log any attempt (successful or not) to run an application. This is very useful when tracking who made that one fatal mistake that took 10 hours to fix :)


The app-admin/sudo package allows the system administrator to grant permission to other users to execute one or more applications they would normally have no right to. Unlike using the setuid bit on these applications sudo gives a more fine-grained control on who can execute a certain command and when.

With sudo a clear list can be made of who can execute a certain application. If the setuid bit is set on an executable, any user would be able to run the application (or any user of a certain group, depending on the permissions used). With sudo the user can (and probably should) be required to provide a password in order to execute the application.

The sudo configuration is managed by the /etc/sudoers file.

The /etc/sudoers should never be edited through nano /etc/sudoers or vim /etc/sudoers, or any other editor that is normally used. When altering the /etc/sudoers file, always use visudo. This tool makes sure that no two system administrators are editing this file at the same time, preserves the permissions on the file, and performs some syntax checking to make sure no fatal mistakes in the file.


sudo 最难的部分是 /etc/sudoers 的语法。基本语法如下:

代码 基础 /etc/sudoers 语法
user  host = command

This line tells sudo that the user, identified by user and logged in on the system host, can execute the command command (which can also be a comma-separated list of allowed commands).

A more real-life example might make this more clear: To allow the user larry to execute emerge when he is logged in on localhost:

代码 /etc/sudoers 实例
larry  localhost = /usr/bin/emerge
主机名必须与 hostname 命令返回的名称匹配。
在最简单的情况下,命令必须是可执行文件的完整限定路径:是 /usr/bin/emerge 而不仅仅是 emerge。路径也可以包含通配符,并且可以引用整个目录。有关详细信息,请参阅手册。
不要让普通用户运行可以提升权限的应用程序。例如,允许用户以 root 身份执行 emerge 可以授予他们完全的 root 访问系统权限,因为可以操纵 emerge 来更改实时文件系统以对用户有利。如果 sudo 用户不受信任,请不要授予他们任何其他权限。

The user name can also be substituted with a group name, in which case the name is prefaced by a % sign. For instance, to allow any one in the wheel group to execute emerge:

代码 允许任何 wheel 组成员执行 emerge
%wheel  localhost = /usr/bin/emerge

To enable more than one command for a given user on a given machine, multiple commands can be listed on the same line. For instance, to allow larry to not only run emerge but also ebuild and emerge-webrsync as root:

代码 多个命令
larry  localhost = /usr/bin/emerge, /usr/bin/ebuild, /usr/sbin/emerge-webrsync

The precise command line can also be specified (including parameters and arguments) not just the name of the executable. This is useful to restrict the use of a certain tool to a specified set of command options. The sudo tool allows shell-style wildcards (AKA meta or glob characters) to be used in path names as well as command-line arguments in the sudoers file. Note that these are not regular expressions.

Here is an example of sudo from the perspective of a first-time user of the tool who has been granted access to the full power of emerge:

user $sudo emerge -uDN world
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.
Password: ## (Enter the user password, not root!)

The password that sudo requires is the user's own password. This is to make sure that no terminal that is accidentally left open to others is abused for malicious purposes.

sudo 不会改变 ${PATH} 变量:在 sudo 之后放置的任何命令都在“用户自己的环境”中执行。因此如果用户想要在 /sbin 中运行工具,举例来说,用户必须向 sudo 提供命令的完整路径,如下所示:
user $sudo /usr/sbin/emerge-webrsync

LDAP 的基本语法

LDAP 需要 ldappam USE 标志的支持。

将 sudo 与 LDAP 一起使用时,sudo 也会从 LDAP 服务器读取配置。所以需要编辑两个文件。

文件 /etc/ldap.conf.sudo请在完成后使用 chmod 400
# See ldap.conf(5) and README.LDAP for details
# This file should only be readable by root
# supported directives: host, port, ssl, ldap_version
# uri, binddn, bindpw, sudoers_base, sudoers_debug
# tls_{checkpeer,cacertfile,cacertdir,randfile,ciphers,cert,key}
port 389
base dc=example,dc=com
uri ldap://
#uri ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock
ldap_version 3
#ssl start_tls
sudoers_base ou=SUDOers,dc=example,dc=com
#sudoers_debug 2
bind_policy soft
文件 /etc/nsswitch.conf请添加 sudoers 行
sudoers:     ldap files

需要为 sudo 添加以下 LDAP 条目。

It was design so that the sudoers branch are on top of the tree for security reason. This allows a different access right from LDAP to read/write to this branch
代码 LDAP entry for sudo
version: 1
DN: ou=SUDOers,dc=example,dc=com
objectClass: organizationalUnit
objectClass: top
objectClass: domainRelatedObject
ou: SUDOers
DN: cn=defaults,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: env_reset
DN: cn=root,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: root
sudoCommand: ALL
sudoHost: ALL
sudoUser: root
DN: cn=%wheel,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: %wheel
sudoCommand: ALL
sudoHost: ALL
sudoOption: !authenticate
sudoUser: %wheel
代码 LDAP entry for wheel group
version: 1
DN: cn=wheel,ou=Group,dc=example,dc=com
objectClass: top
objectClass: posixGroup
cn: wheel
description: Wheel Group
gidNumber: 10
memberUid: useradmin1
memberUid: root

The configuration on the sudoer on LDAP are similar to files with some different. Please read more about sudo with LDAP on the link below.[1]


In larger environments having to enter all users over and over again (or hosts, or commands) can be a daunting task. To ease the administration of /etc/sudoers aliases can defined. The format to declare aliases is quite simple:

代码 Declaring aliases in /etc/sudoers
Host_Alias hostalias = hostname1, hostname2, ...
User_Alias useralias = user1, user2, ...
Cmnd_Alias cmndalias = command1, command2, ...

One alias that always works, for any position, is the ALL alias (to make a good distinction between aliases and non-aliases it is recommended to use capital letters for aliases). The ALL alias is an alias to all possible settings.

A sample use of the ALL alias to allow any user to execute the shutdown command if he is logged on locally is:

代码 Allowing any user to execute shutdown
ALL  localhost = /sbin/shutdown

Another example is to allow the user larry to execute the emerge command as root, regardless of where he is logged in from:

代码 Allowing a user to run an application regardless of his location
larry   ALL = /usr/bin/emerge

More interesting is to define a set of users who can run software administrative applications (such as emerge and ebuild) on the system and a group of administrators who can change the password of any user, except root!

代码 Using aliases for users and commands
User_Alias  SOFTWAREMAINTAINERS = larry, john, danny
User_Alias  PASSWORDMAINTAINERS = larry, sysop
Cmnd_Alias  SOFTWARECOMMANDS    = /usr/bin/emerge, /usr/bin/ebuild
Cmnd_Alias  PASSWORDCOMMANDS    = /usr/bin/passwd [a-zA-Z0-9_-]*, !/usr/bin/passwd root

Non-root execution

It is also possible to have a user run an application as a different, non-root user. This can be very interesting when running applications as a different user (for instance apache for the web server) and want to allow certain users to perform administrative steps as that user (like killing zombie processes).

Inside /etc/sudoers list the user(s) in between ( and ) before the command listing:

代码 Non-root execution syntax
users  hosts = (run-as) commands

For instance, to allow larry to run the kill tool as the apache or gorg user:

代码 Non-root execution example
Cmnd_Alias KILL = /bin/kill, /usr/bin/pkill
larry   ALL = (apache, gorg) KILL

With this set, the user can run sudo -u to select the user he wants to run the application as:

user $sudo -u apache pkill apache

An alias can set for the user to run an application as using the Runas_Alias directive. Its use is identical to the other _Alias directives we have seen before.

Passwords and default settings

By default, sudo asks the user to identify himself using his own password. Once a password is entered, sudo remembers it for 5 minutes, allowing the user to focus on his tasks and not repeatedly re-entering his password.

Of course, this behavior can be changed: set the Defaults: directive in /etc/sudoers to change the default behavior for a user.

For instance, to change the default 5 minutes to 0 (never remember):

代码 Changing the timeout value
Defaults:larry  timestamp_timeout=0

A setting of -1 would remember the password indefinitely (until the system reboots).

A different setting would be to require the password of the user that the command should be run as and not the users' personal password. This is accomplished using runaspw. In the following example we also set the number of retries (how many times the user can re-enter a password before sudo fails) to 2 instead of the default 3:

代码 需要 root 密码而不是用户密码
Defaults:john   runaspw, passwd_tries=2

另一个有趣的功能是保持 DISPLAY 变量集,以便可以执行图形工具:

代码 保持 DISPLAY 变量有效
Defaults:john env_keep=DISPLAY

Dozens of default settings can changed using the Defaults: directive. Fire up the sudoers manual page and search for Defaults.

To allow a user to run a certain set of commands without providing any password whatsoever, start the commands with NOPASSWD:, like so:

代码 Allowing emerge to be run as root without asking for a password
larry     localhost = NOPASSWD: /usr/bin/emerge

Bash completion

Users that want bash completion with sudo need to run this once.

user $echo "complete -cf sudo" >> $HOME/.bashrc

Zshell completion

Users that want zsh completion for sudo can set the following in .zprofile and .zshrc respectively

文件 .zprofileAdding zshell completion
if [[ $EUID != 0 ]]; then
    typeset -xT SUDO_PATH sudo_path
    typeset -U sudo_path
    alias sudo="sudo env PATH=\"SUDO_PATH:$PATH\""
文件 .zshrcAdding zshell completion
zstyle ':completion:*:sudo:*' environ PATH="$SUDO_PATH:$PATH"

With the above change, all commands in the /sbin, /usr/sbin and /usr/local/sbin locations will be available to the shell for completion when the command is prefaced with 'sudo'.

This alias will disrupt sudo configurations specifying commands like
代码 Allowing emerge to be run as root without asking for a password
larry     localhost = NOPASSWD: /usr/bin/emerge



要列出当前用户的能力,请运行 sudo -l

user $sudo -l
User larry may run the following commands on this host:
    (root)   /usr/libexec/xfsm-shutdown-helper
    (root)   /usr/bin/emerge
    (root)   /usr/bin/passwd [a-zA-Z0-9_-]*
    (root)   !/usr/bin/passwd root
    (apache) /usr/bin/pkill
    (apache) /bin/kill

/etc/sudoers 中的任何命令不需要输入密码,也不需要密码来列出条目。对于其它命令,sudo 会要求输入密码。


默认情况下,如果用户输入了他们的密码以向 sudo 验证他们自己,它会被记住 5 分钟。如果用户想延长这段时间,他可以运行 sudo -v 来重置时间戳,这样 sudo 在再次要求输入密码之前还需要 5 分钟。

user $sudo -v

反之则是使用 sudo -k 终止时间戳。

  • doas — provides a way to perform commands as another user.
  • su — used to adopt the privileges of other users from the system