在無圖形介面的 Linux 伺服器上使用 Git 存取 HTTP/HTTPS 遠端倉庫時,需處理認證儲存與加密問題。本文說明使用 .netrc 搭配 GPG 加密、Git Credential Helper 的標準設定流程。

git-credential-netrc 腳本置於 Git libexec 目錄(/usr/libexec/git-core/ 或 /usr/lib/git-core/)~/.netrcmachine git.example.com
login your@email.com
password yourpassword
gpg --gen-key
# 選擇 RSA 1024/2048,設定過期時間、姓名、信箱、密碼
gpg --list-keys # 確認金鑰 ID
.netrc 為 .netrc.gpggpg -o ~/.netrc.gpg -er your_key_id ~/.netrc
# 驗證可解密
gpg -d ~/.netrc.gpg
# 刪除明文檔
rm ~/.netrc
git config --global credential.helper store
首次輸入帳密後永久快取於 ~/.git-credentials(明文)。
git config --global credential.helper 'netrc -f ~/.netrc.gpg -d'
或編輯 ~/.gitconfig:
[credential]
helper = netrc -f ~/.netrc.gpg -d
[user]
name = Your Name
email = your@email.com
git clone https://git.example.com:port/project/my_project.git
首次會提示輸入 GPG 解密密碼,後續自動使用。
若伺服器支援 SSH,建議改用 SSH 金鑰認證:
ssh-keygen -t ed25519
ssh-copy-id user@git.example.com
git clone git@git.example.com:project/my_project.git
SSH 方式更安全、無需管理密碼檔、支援代理轉發,為生產環境首選。