sudo 命令是否暂时将 $PATH 更改为 root 的?

Tim*_*Tim 6 sudo path

  1. sudo <command>用户登录会话下运行时,会在运行期间更改$PATH为 root 用户吗?$PATHsudo <command>
  2. 如果<command>依赖于用户的$PATH,而不是根的$PATH,用户如何运行sudo <command>成功?

cuo*_*glm 9

在用户登录会话下运行 sudo 时,是否会在运行 sudo 期间将 $PATH 更改为 root 的 $PATH ?

sudo将改变$PATH变量,取决于您的安全策略。从sudo 手册页

PATH
    May be overridden by the security policy.
Run Code Online (Sandbox Code Playgroud)

在大多数系统中,env_reset选项是默认启用,这将导致与含有一个最小的环境中执行的命令TERMPATHHOMESHELLLOGNAMEUSERUSERNAME除了从调用过程变量允许通过env_checkenv_keepsudoers的选项。

出于安全原因,/etc/sudoerssecure_path选项来设置安全PATHsudo

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Run Code Online (Sandbox Code Playgroud)

如果依赖于用户的 $PATH,而不是 root 的 $PATH,那么用户如何成功运行 sudo?

因为PATH运行时可以保留用户的sudo。你总是可以这样做:

sudo env "PATH=$PATH" <command>
Run Code Online (Sandbox Code Playgroud)


Mic*_*mer 6

这实际上取决于配置。有一个env_reset选项sudoers,与env_checkand结合env_delete,控制是否替换、扩展或传递部分或所有环境变量,包括PATH.

默认行为是env_reset启用和重置PATH。该值PATH设置为可以通过secure_path选项控制,否则由用户配置决定。

您可以禁用env_reset或添加PATHenv_keep以更改该行为,但请注意,它可能不会产生您想要的整体效果 - sbinroot 中的目录 ( )PATH通常不在您的用户中。您可以启用setenv,而不是允许的单次执行重写环境sudo使用的-E选项sudo

所有这些都可以在您的发行版的默认配置中进行更改。运行sudo visudo以查看当前sudoers文件中的内容。


有替代方法。一种简单的方法是使用sudo的内置环境变量设置或env

sudo PATH="$PATH" command ...
sudo env PATH="$PATH" command ...
Run Code Online (Sandbox Code Playgroud)

都将使用您当前用户的PATH. 您也可以以相同的方式在那里设置其他变量,这通常很有用。您的配置可能不允许其中之一。


Rus*_*mov 5

您是否需要获得交互式登录 root shell?

sudo -H -i

来自man sudo

 -H          The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the
             target user (root by default) as specified by the password database.  Depending on the policy, this may be the default
             behavior.


 -i [command]
             The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a
             login shell.  This means that login-specific resource files such as .profile or .login will be read by the shell.  If a
             command is specified, it is passed to the shell for execution via the shell's -c option.  If no command is specified,
             an interactive shell is executed.  sudo attempts to change to that user's home directory before running the shell.  The
             security policy shall initialize the environment to a minimal set of variables, similar to what is present when a user
             logs in.  The Command Environment section in the sudoers(5) manual documents how the -i option affects the environment
             in which a command is run when the sudoers policy is in use.
Run Code Online (Sandbox Code Playgroud)