Git 安裝與 SSH Key 設定教學:在 VPS 上實現安全高效的程式碼部署

GitSSH KeyGitHubGitLabVPS安裝設定程式碼管理自動化部署教學SSH

本文將引導你在 VPS 上完成 Git 的基礎安裝與 SSH Key 的產生與設定,讓你可以安全、快速地將程式碼從 GitHub 或 GitLab 同步到伺服器上。

Terminal — ssh-keygen $ ssh-keygen -t ed25519 Generating public/private ed25519 key pair. Enter file in which to save the key: (Enter) Your identification has been saved in id_ed25519 Your public key has been saved in id_ed25519.pub $

為什麼要在 VPS 上使用 SSH Key?

在頻繁進行部署時,每次執行 git pull 都要輸入帳號密碼既麻煩又不安全。透過 SSH Key 非對稱加密機制,你可以實現免密碼但高度安全的身份驗證,這對於自動化部署流程(CI/CD)尤為重要。

步驟一:安裝 Git

在 Ubuntu 或 Debian 系統上,安裝 Git 非常簡單:

sudo apt update
sudo apt install git -y
git --version

安裝後,請設定你的使用者資訊(這會顯示在 commit 紀錄中):

git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"

步驟二:產生 SSH Key

請在 VPS 終端機執行以下指令產生一對新的金鑰:

ssh-keygen -t ed25519 -C "your_email@example.com"

系統會詢問儲存路徑與密碼,直接按 Enter 鍵使用預設值即可。完成後,金鑰會儲存在 ~/.ssh/ 目錄下。

步驟三:將公鑰加入 GitHub/GitLab

  1. 讀取你的公鑰內容:cat ~/.ssh/id_ed25519.pub
  2. 將顯示出的整串字串(以 ssh-ed25519 開頭)複製起來。
  3. 登入 GitHub → Settings → SSH and GPG keys → New SSH key。
  4. 將內容貼入並儲存。

步驟四:測試連線

最後,測試看看是否能成功連線到 GitHub:

ssh -T git@github.com

如果看到 Hi username! You've successfully authenticated,代表你已經完成設定,現在可以透過 git clone git@github.com:... 進行免密碼操作了。

常見問題

Q:權限不足無法 clone?
請確認你的 .ssh 目錄權限為 700,私鑰檔案(id_ed25519)權限為 600。如果權限過於開放,SSH 會出於安全考量拒絕使用金鑰。

Q:如何管理多個 Git 帳號?
你可以透過建立 ~/.ssh/config 檔案來設定不同 Host 使用對應的金鑰檔案。更多進階設定可參考我們的 SSH 連線教學

需要主機來實作?

侃瑞科技提供 cPanel 虛擬主機與 VPS,教學裡的操作開箱即用。

查看方案 →
LINE 諮詢