命令行工具使用代理的方法

命令行工具默认是不使用系统代理的,因此即便我们在代理工具中启用了系统代理选项,命令行工具依然不会使用代理通信。

用 curl 或 wget 下载 GitHub 上存在的文件时出现 443 错误就是没有挂代理导致的。

使用环境变量(推荐)

很多 Linux 和 Unix 命令行工具(比如 curl,wget,lynx 等)使用名为 http_proxyhttps_proxyall_proxy 等的环境变量来获取代理信息。它允许你通过代理服务器来连接那些基于文本的会话和应用。

export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890
export all_proxy=socks5://127.0.0.1:7891

如果你的代理服务器需要用户名和密码:

export http_proxy=http://user:password@proxy-address:port

使用命令选项

# 通过代理服务器访问 URL
wget -e http_proxy=127.0.0.1:7890 <url> # 如果是 https 内容,需要使用 https_proxy

curl -x 127.0.0.1:7890 <url>
curl -x socks5://127.0.0.1:7891 <url>
  • 使用 protocol:// 的格式指定协议。若不指定,则默认值为 http://
  • 端口默认为 1080

设置配置文件

~/.curlrc 中添加以下内容:

proxy = 127.0.0.1
proxy-user = "user:passward"

此后使用 curl 都会默认走代理。

如果临时不需要代理使用以下参数:

curl --noproxy "*" url

设置 Linux 全局代理别名

~/.bashrc 中添加以下内容:

alias set_proxy="export http_proxy='http://127.0.0.1:7890' https_proxy=$http_proxy all_proxy='socks5://127.0.0.1:7891'; echo 'Proxy on'"
alias unset_proxy="unset http_proxy https_proxy all_proxy; echo 'Proxy off'"

以后需要启用代理时,输入 set_proxy 即可一步设置代理环境变量。不需要走代理时,输入 unset_proxy 即可删除代理环境变量。

posted @ 2024-04-19 17:08  Undefined443  阅读(895)  评论(0编辑  收藏  举报