为什么 wget 在使用 sudo 执行时会出错,但没有它就可以正常工作?

h0c*_*355 22 sudo bash wget

我尝试了以下命令:

$ wget -q --tries=10 --timeout=20 --spider http://google.com
Run Code Online (Sandbox Code Playgroud)

(来自this SO post。我想在bash中检查我的互联网连接。)

我得到以下输出:

Spider mode enabled. Check if remote file exists.
--2015-09-28 09:55:50--  http://google.com/
Connecting to 127.0.0.1:3128... connected.
Proxy request sent, awaiting response... 302 Found
Location: http://www.google.de/?gfe_rd=cr&ei=k_IIVreaN-yH8Qfe1Yu4CA [following]
Spider mode enabled. Check if remote file exists.
--2015-09-28 09:55:50--  http://www.google.de/?gfe_rd=cr&ei=k_IIVreaN-yH8Qfe1Yu4CA
Connecting to 127.0.0.1:3128... connected.
Proxy request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Remote file exists and could contain further links,
but recursion is disabled -- not retrieving.
Run Code Online (Sandbox Code Playgroud)

似乎没问题,但是运行 cmd 时sudo,我收到了这个:

Spider mode enabled. Check if remote file exists.
--2015-09-28 09:55:27--  http://google.com/
Resolving google.com (google.com)... failed: Name or service not known.
wget: unable to resolve host address ‘google.com’
Run Code Online (Sandbox Code Playgroud)

我在脚本中需要这一行,我用sudo它来调用它,所以它总是失败。

有人能告诉我这是什么原因吗?我该如何解决这个问题?

Del*_*tik 39

您在您的环境中定义了一个代理。你的似乎是127.0.0.1:3128

运行时sudo,没有传递代理环境变量,这就是为什么不能直接解析google.com.

您可以使用以下命令查看您在环境变量中定义的代理/代理:

env | grep proxy
Run Code Online (Sandbox Code Playgroud)

关于询问 Ubuntu 的附加信息

注意:如果你想sudo传递 HTTP 代理环境变量,试试这个:

sudo http_proxy="$http_proxy" wget -q --tries=10 --timeout=20 --spider http://google.com
Run Code Online (Sandbox Code Playgroud)

您还可以使用sudo -E以下方法传递所有环境变量:

sudo -E wget -q --tries=10 --timeout=20 --spider http://google.com
Run Code Online (Sandbox Code Playgroud)

Stack Overflow 有其他选项可以在sudoing时保持环境变量。

  • 您还可以使用 `sudo -E` 来保留环境变量 (7认同)
  • 好的,非常感谢您不仅发布了答案,还发布了解释链接。完美地为我工作。 (5认同)
  • 仅通过 http_proxy,`sudo http_proxy=$http_proxy wget ...` 不是更好吗?如果您在任何脚本中使用它,则在代理更改时您不必更改它。 (4认同)