git不需要打帳號密碼push(SSH)
Contents
每次 git push 都要輸入帳號密碼非常麻煩,尤其在 CI/CD 或自動化流程中更是問題。Git 提供多種方式讓你免除反覆輸入的困擾,各有不同的安全性考量。
方式一:SSH Key(最推薦)
SSH Key 是最安全也最常用的方式,透過公私鑰配對認證,不需要傳送任何密碼。
產生 SSH Key
|
|
預設會在 ~/.ssh/ 目錄產生 id_ed25519(私鑰)和 id_ed25519.pub(公鑰)。
將公鑰加到 GitHub / GitLab
|
|
到 GitHub → Settings → SSH and GPG keys → New SSH key,貼上公鑰。
測試連線
|
|
確認 Remote URL 使用 SSH 格式
|
|
重要:SSH Key 認證只對 SSH 格式的 Remote URL 有效(
git@github.com:...),HTTPS 格式(https://github.com/...)無效。
方式二:Credential Cache(暫時緩存)
在記憶體中暫存密碼,不寫入磁碟,適合公用電腦短期使用:
|
|
輸入一次密碼後,在指定時間內不需要再次輸入。時間到後緩存自動清除。
方式三:Credential Store(明文儲存)
將帳號密碼以明文形式儲存在本機檔案(~/.git-credentials):
|
|
第一次 push 輸入帳號密碼後,之後都不需要再輸入。
安全警告:密碼以明文儲存,任何能讀取該檔案的人都能看到密碼。不建議在共用機器或有安全疑慮的環境使用。
方式四:Windows Credential Manager
在 Windows 上,Git for Windows 預設整合 Windows 憑證管理員(Credential Manager):
|
|
密碼以加密方式儲存在 Windows Credential Manager(可在「控制台 → 認證管理員」中查看)。第一次 push 時會彈出登入視窗,之後自動記住。
各方式安全性比較
| 方式 | 安全性 | 便利性 | 適合場景 |
|---|---|---|---|
| SSH Key | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 個人電腦、CI/CD |
| Credential Cache | ⭐⭐⭐⭐ | ⭐⭐⭐ | 短期使用 |
| Windows Credential Manager | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | Windows 環境 |
| Credential Store(明文) | ⭐ | ⭐⭐⭐⭐⭐ | 不建議使用 |