Mac 產生 SSH Key 免密碼進入主機 & 推送 GitHub


#Mac#Linux#SSH Key

SSH Key 可以讓對方 server 快速驗證你的身份,不用再輸入帳號密碼,方便的好東西。
使用 SSH Key 需要兩步驟:

  1. 本機產生公鑰及私鑰,私鑰請自行保存好!
  2. 將公鑰放置 server 

產生


開啟你的 Terminal,執行

ssh-keygen

會詢問你要不要自訂存放位置,我是直接 Enter 使用預設

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/mtsung/.ssh/id_rsa):

會詢問你要不要定義密碼,這樣你每次使用都要輸入密碼,我很懶所以連按了兩次 Enter

Enter passphrase (empty for no passphrase):
Enter same passphrase again:

你的資料夾內就會產生一組私鑰 (id_rsa) 與公鑰 (id_rsa.pub)

Server 設定 SSH Key 


把公鑰 (id_rsa.pub) cat 出來,複製內容

mtsung@MTsung-Toby-MacBook ~ % cat .ssh/id_rsa.pub
ssh-rsa AAAAB3Nza......略......6gH1ExU51ochUsKME= mtsung@caimincongdeAir

連上 Server 將剛剛複製的內容貼到 ~/.ssh/authorized_keys 最後一行

echo "ssh-rsa AAAAB3Nza......略......6gH1ExU51ochUsKME= mtsung@caimincongdeAir" > ~/.ssh/authorized_keys

GitHub 設定 SSH Key 


登入你的 GitHub > Settings > SSH and GPG keys > New SSH key

  1. 設定自己看得懂的名稱
  2. 選擇 Authentication Key
  3. 貼上你的公鑰
  4. 新增成功


參考:
https://xenby.com/b/220-%E6%95%99%E5%AD%B8-%E7%94%A2%E7%94%9Fssh-key%E4%B8%A6%E4%B8%94%E9%80%8F%E9%81%8Ekey%E9%80%B2%E8%A1%8C%E5%85%8D%E5%AF%86%E7%A2%BC%E7%99%BB%E5%85%A5