如何在使用SUDO时保持环境variables

当我用sudo使用任何命令时,环境variables不在那里。 例如,设置HTTP_PROXY后,命令wget没有sudo可以正常工作。 但是,如果我键入sudo wget它说它不能绕过代理设置。

首先你需要export HTTP_PROXY 。 其次,你需要仔细阅读man sudo ,并注意-E标志。 这工作:

 $ export HTTP_PROXY=foof $ sudo -E bash -c 'echo $HTTP_PROXY' 

以下是手册页中的引用:

 -E, --preserve-env Indicates to the security policy that the user wishes to reserve their existing environment variables. The security policy may eturn an error if the user does not have permission to preserve the environment. 

诀窍是通过sudo visudo命令将环境variables添加到sudoers文件中并添加以下行:

 Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy" 

取自ArchLinux维基 。

对于Ubuntu 14,您需要在单独的行中指定,因为它会返回多variables行的错误:

 Defaults env_keep += "http_proxy" Defaults env_keep += "https_proxy" Defaults env_keep += "HTTP_PROXY" Defaults env_keep += "HTTPS_PROXY" 

对于您希望一次性提供的variables,您可以将其作为命令的一部分。

 sudo http_proxy=$http_proxy wget "http://stackoverflow.com" 

你也可以把Ahmed Aswani的答案中的两个env_keep语句合并成一个单独的语句:

Defaults env_keep += "http_proxy https_proxy"

你也应该考虑只为一个命令指定env_keep ,像这样:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"