Contents

git不需要打帳號密碼push(SSH)

每次 git push 都要輸入帳號密碼非常麻煩,尤其在 CI/CD 或自動化流程中更是問題。Git 提供多種方式讓你免除反覆輸入的困擾,各有不同的安全性考量。

方式一:SSH Key(最推薦)

SSH Key 是最安全也最常用的方式,透過公私鑰配對認證,不需要傳送任何密碼。

產生 SSH Key

1
2
3
ssh-keygen -t ed25519 -C "your_email@example.com"
# 舊版 Git 用 RSA:
# ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

預設會在 ~/.ssh/ 目錄產生 id_ed25519(私鑰)和 id_ed25519.pub(公鑰)。

將公鑰加到 GitHub / GitLab

1
2
# 複製公鑰內容
cat ~/.ssh/id_ed25519.pub

到 GitHub → Settings → SSH and GPG keys → New SSH key,貼上公鑰。

測試連線

1
2
ssh -T git@github.com
# 成功回應:Hi username! You've successfully authenticated...

確認 Remote URL 使用 SSH 格式

1
2
3
4
5
# 查看目前 remote url
git remote -v

# 如果是 https:// 開頭,改成 SSH 格式
git remote set-url origin git@github.com:username/repo.git

重要:SSH Key 認證只對 SSH 格式的 Remote URL 有效(git@github.com:...),HTTPS 格式(https://github.com/...)無效。

方式二:Credential Cache(暫時緩存)

在記憶體中暫存密碼,不寫入磁碟,適合公用電腦短期使用:

1
2
3
4
5
# 緩存 15 分鐘(預設)
git config --global credential.helper cache

# 指定緩存時間(秒)
git config --global credential.helper 'cache --timeout=3600'

輸入一次密碼後,在指定時間內不需要再次輸入。時間到後緩存自動清除。

方式三:Credential Store(明文儲存)

將帳號密碼以明文形式儲存在本機檔案(~/.git-credentials):

1
git config --global credential.helper store

第一次 push 輸入帳號密碼後,之後都不需要再輸入。

安全警告:密碼以明文儲存,任何能讀取該檔案的人都能看到密碼。不建議在共用機器或有安全疑慮的環境使用

方式四:Windows Credential Manager

在 Windows 上,Git for Windows 預設整合 Windows 憑證管理員(Credential Manager):

1
2
3
git config --global credential.helper manager
# 或新版 Git for Windows
git config --global credential.helper manager-core

密碼以加密方式儲存在 Windows Credential Manager(可在「控制台 → 認證管理員」中查看)。第一次 push 時會彈出登入視窗,之後自動記住。

各方式安全性比較

方式 安全性 便利性 適合場景
SSH Key ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ 個人電腦、CI/CD
Credential Cache ⭐⭐⭐⭐ ⭐⭐⭐ 短期使用
Windows Credential Manager ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ Windows 環境
Credential Store(明文) ⭐⭐⭐⭐⭐ 不建議使用

參考資料