Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 命令列環境下 Git over HTTPS 認證設定完整指南:.netrc + GPG 加密 + credential helper 實戰

編輯:關於 Linux

在無圖形介面的 Linux 伺服器/CI 環境中,Git 僅能透過 HTTPS 協定存取遠端倉庫。為避免每次輸入帳密,並保護明文憑證不落盤,本文建立一套 .netrc + GPG 加密 + Git credential helper 的安全認證體系。

Git HTTPS 認證流程圖

完整設定流程

1. 建立明文憑證檔 ~/.netrc

vim ~/.netrc
# 內容 (權限務必 600)
machine git.example.com
login your@email.com
password your_strong_password
chmod 600 ~/.netrc

2. 產生 GPG 金鑰對

gpg --full-generate-key
# 選擇: (1) RSA and RSA → 3072 bits → 1y → 確認
# 輸入真實姓名、Email、註解、Passphrase (強建議設定)
gpg --list-keys
# 記下 pub 金鑰 ID (如 ABCD1234)

3. 加密 .netrc → ~/.netrc.gpg

gpg -o ~/.netrc.gpg -e -r ABCD1234 ~/.netrc
# -e 加密, -r 指定接收者金鑰 ID

# 驗證解密
gpg -d ~/.netrc.gpg
# 輸入 Passphrase 後應顯示明文內容

# 刪除明文檔
shred -u ~/.netrc

4. 設定 Git Credential Helper

# 方式一: 純記憶體快取 (預設 15 分鐘)
git config --global credential.helper 'cache --timeout=900'

# 方式二: 使用加密 .netrc.gpg (需 git-credential-netrc 腳本)
git config --global credential.helper 'netrc -f ~/.netrc.gpg -d'
# -d: 解密後刪除記憶體副本

注意:git-credential-netrc 需放置於 Git libexec/git-core/ 目錄 (通常 /usr/lib/git-core/),Git 2.2.2+ 內建支援。

5. 完善 ~/.gitconfig

[user]
    name = Your Name
    email = your@email.com
[core]
    excludesfile = ~/.gitignore_global
[credential]
    helper = netrc -f ~/.netrc.gpg -d
    # helper = cache --timeout=900

實戰驗證

git clone https://git.example.com:port/project/repo.git
# 首次會提示 GPG Passphrase (若使用 netrc helper)
# 後續操作無需輸入帳密

進階:多帳號/多主機管理

# ~/.netrc 可包含多組 machine
machine github.com
login user1
password ghp_xxx

machine gitlab.company.com
login user2
password glpat_yyy

# GPG 加密同樣處理,Git 會自動匹配 machine 對應憑證

安全最佳實踐

  • GPG 金鑰設定 **Passphrase**,搭配 gpg-agent 快取 (預設 10 分鐘)
  • 定期輪換 Git 存取權杖 (Personal Access Token) 而非帳號密碼
  • CI/CD 環境建議使用專用 **Deploy Token** / **Deploy Key** (SSH)
  • ~/.netrc.gpg 權限設為 600,目錄 700
  • 啟用 git config --global credential.useHttpPath true 區分同主機不同路徑憑證

此方案在「無法使用 SSH 金鑰」的受限環境 (企業防火牆僅開 443、代理伺服器、舊版 Git 伺服器) 下,提供兼具便利性與安全性的 HTTPS 認證解決方案。

Copyright © Windows教程網 All Rights Reserved