企業內網環境下,Ubuntu/Debian 伺服器需透過**需要帳號密碼驗證的 HTTP/HTTPS Proxy** 連網。若僅在環境變數 http_proxy/https_proxy 設定代理,apt-get update/install 仍會報錯:
Err:1 https://archive.ubuntu.com/ubuntu focal InRelease
407 Proxy Authentication Required
Reading package lists... Done
W: Failed to fetch https://archive.ubuntu.com/ubuntu/dists/focal/InRelease 407 Proxy Authentication Required
原因:**APT 不直接讀取環境變數**,需在 /etc/apt/apt.conf (或 /etc/apt/apt.conf.d/99proxy) 明確配置含認證資訊的代理 URL。
.d 目錄分離管理):cat > /etc/apt/apt.conf.d/99proxy <<'EOF'
Acquire::http::Proxy "https://username:password@proxy.server:port/";
Acquire::https::Proxy "https://username:password@proxy.server:port/";
Acquire::ftp::Proxy "ftp://username:password@proxy.server:port/";
EOF
關鍵點:
username:password 為代理驗證帳密 (特殊字符需 URL 編碼,如 @ → %40)proxy.server:port 為代理伺服器位址與埠 (如 10.0.0.5:3128)https:// 協定 (CONNECT 隧道),除非代理明確要求 https:/// 建議保留Acquire::http::Proxy "https://DOMAIN\\username:password@proxy.server:port/";
# 雙反斜線轉義
apt-get update
# 應無 407 錯誤,正常抓取套件清單
若內部有私有 APT 源 (如 repo.company.local) 不需走代理,可用 Acquire::http::Proxy:: 針對主機名設定例外:
cat > /etc/apt/apt.conf.d/99proxy <<'EOF'
# 預設走代理
Acquire::http::Proxy "https://user:pass@proxy:3128/";
Acquire::https::Proxy "https://user:pass@proxy:3128/";
# 內網源直連 (不走代理)
Acquire::http::Proxy::repo.company.local "DIRECT";
Acquire::https::Proxy::repo.company.local "DIRECT";
# 特定外網源強制直連 (如內網鏡像站)
Acquire::http::Proxy::mirrors.aliyun.com "DIRECT";
Acquire::https::Proxy::mirrors.aliyun.com "DIRECT";
EOF
| 現象 | 原因 | 解決 |
|---|---|---|
| 仍報 407 | 帳密錯誤、特殊字符未編碼、代理埠錯誤 | 用 curl -x https://user:pass@proxy:port https://httpbin.org/ip 驗證代理本身可用 |
| HTTPS 源失敗 | HTTPS 代理協定寫錯 (需用 https:// 建立 CONNECT 隧道) | 統一用 https:// 協定配置 https::Proxy |
| 配置不生效 | 檔案權限、語法錯誤 (少分號、引號未閉合) | apt-config dump | grep -i proxy 驗證實際生效配置 |
| DNS 解析失敗 | 代理需代理端解析 DNS,但代理無法解析外網域名 | 確認代理 DNS 設定,或在 /etc/hosts 加入常用源 IP |
/etc/apt/apt.conf.d/99proxy 含明文密碼,**權限務必設為 600**:chmod 600 /etc/apt/apt.conf.d/99proxyAPT 代理認證配置核心:**/etc/apt/apt.conf.d/99proxy 明文指定含帳密的代理 URL、HTTPS 也用 https:// 協定、內網源例外用 DIRECT、檔案權限 600**。配置正確後,apt-get update/install/upgrade 即可在受限網路環境下正常運作。