萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 命令列環境下基於 HTTP 協議的 Git 認證與設定完整教學

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

前置需求

  • Git 2.2.2+ 版本
  • git-credential-netrc 腳本置於 Git libexec 目錄(/usr/libexec/git-core/ 或 /usr/lib/git-core/)

步驟 1:建立明文認證檔 ~/.netrc

machine git.example.com
login your@email.com
password yourpassword

步驟 2:產生 GPG 金鑰對

gpg --gen-key
# 選擇 RSA 1024/2048,設定過期時間、姓名、信箱、密碼
gpg --list-keys  # 確認金鑰 ID

步驟 3:加密 .netrc 為 .netrc.gpg

gpg -o ~/.netrc.gpg -er your_key_id ~/.netrc
# 驗證可解密
gpg -d ~/.netrc.gpg
# 刪除明文檔
rm ~/.netrc

步驟 4:設定 Git Credential Helper

方式 A:快取模式(不需 GPG,適合單機開發)

git config --global credential.helper store

首次輸入帳密後永久快取於 ~/.git-credentials(明文)。

方式 B:GPG 加密模式(安全,需輸入 GPG 密碼)

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

步驟 5:測試 Clone

git clone https://git.example.com:port/project/my_project.git

首次會提示輸入 GPG 解密密碼,後續自動使用。

進階:SSH 協議替代方案

若伺服器支援 SSH,建議改用 SSH 金鑰認證:

ssh-keygen -t ed25519
ssh-copy-id user@git.example.com
git clone git@git.example.com:project/my_project.git

SSH 方式更安全、無需管理密碼檔、支援代理轉發,為生產環境首選。

copyright © 萬盛學電腦網 all rights reserved