为什么不sudo -E实际上保护我的环境?

我试图sudo一些自定义path中的二进制文件。 当我运行sudo时,这个自定义path被删除,但sudo -E应该保留我的path。 为什么不起作用?

 $ env |  egrep ^ PATH
 PATH = /家庭/ codemonkey / .nvm / V0.6.1 /斌:在/ usr / local / bin目录:在/ usr / bin中:/ bin中:在/ usr /本地/ GAM
 ES:在/ usr /游戏

 $ sudo env |  egrep ^ PATH
 PATH =在/ usr / local / sbin中:在/ usr / local / bin目录:/ usr / sbin目录:在/ usr / bin中:/ sbin目录:/ bin中:在/ usr / X11R6 / bin中

 $ sudo -E env |  egrep ^ PATH
 PATH =在/ usr / local / sbin中:在/ usr / local / bin目录:/ usr / sbin目录:在/ usr / bin中:/ sbin目录:/ bin中:在/ usr / X11R6 / bin中

我知道如何解决它,我只是想知道为什么sudo -E不起作用

您可以设置exempt_group选项来告诉sudo保留该组中用户的PATH

例如,说你的用户在组“sys”中。 将以下内容添加到sudoers文件中

 Defaults exempt_group="sys" 

现在你的用户不会为sudo命令重置PATH-E不需要这个工作)。
有关更多详细信息,请参阅手册页 。

编辑:去必须注意到这是一个不好的答案。 这确实是有效的,但是在玩这个游戏时我没有注意到它的副作用。 它还可以免除该组中的用户input密码。 似乎你不能没有允许这个PATH保存。 我觉得有点愚蠢

提出另一个解决scheme,除了我已经进入。 这只适用于bash(但可以修改其他shell)。

以下是sudo一个包装器,它将查找传递给它的命令。 一旦find命令,它就会将其更改为完全限定的path。
所以实际上, sudo echo hello变成了sudo /bin/echo hello

把下面的内容放在~/.bashrc

 function sudo() { local ARGS declare -a ARGS=() while (( $# )); do if [[ "${1:0:1}" == "-" ]]; then # the argument is a dash-arg; '-s' for example ARGS[${#ARGS[@]}]="$1" if [[ "$1" =~ ^-[pugD]$ ]]; then # these are the arguments that take a parameter, so skip the next ARGS[${#ARGS[@]}]="$2" shift fi shift elif [[ "$1" == *"="* ]]; then # the argument is a env var to set, not a command ARGS[${#ARGS[@]}]="$1" shift else # finally, a command CMD="$(which --skip-alias --skip-functions "$1")" [[ -z "$CMD" ]] && ARGS[${#ARGS[@]}]="$1" || ARGS[${#ARGS[@]}]="$CMD" shift break fi done command sudo "${ARGS[@]}" "$@" } 

请注意,如果您的名称中有一个带有=的命令,它将无法正确处理它。 这是极不可能的,所以我接受了这个警告,以保持简单。

sudoers(5)

  setenv Allow the user to disable the env_reset option from the command line via the -E option. Additionally, environment variables set via the command line are not subject to the restrictions imposed by env_check, env_delete, or env_keep. As such, only trusted users should be allowed to set variables in this manner. This flag is off by default. 

我会看sudoers文件中的选项,因为它们控制着一些sudo行为。

当然,我会查阅sudoers文件的手册页。