跳至主要內容

如何在 Mac 上为 GitHub 设置 SSH Key(2022)

小綿尾巴原创githubgithub大约 5 分钟...约 1414 字

SSH(Secure Shell) 是允许两台电脑之间通过安全连接进行数据交换的网络协议。

在本地电脑生成 SSH Key 私钥,再将 SSH Key 公钥添加到 GitHub,就实现了本地电脑和 GitHub 服务器安全连接,可以把本地仓库推送到 GitHub 远程仓库,或把 GitHub 远程仓库拉取到本地仓库,即两台电脑间的数据交换。

Noted:GitHub 在 2022 年 5 月添加了 SSH 安全性,以往添加 SSH Key 的教程在有些细节处可能不适用,这是 2022 年下半年添加 SSH Key 的教程。

生成 SSH Key

  1. 点开 GitHub open in new window 账号头像下的 Settings
img
img
  1. 找到 Settings 下的 SSH and GPG keys,点击 generating SSH keys,点击后会打开一个新的页面。
img
img
  1. 在新的页面中选择 Generating a new SSH key and adding it to the ssh-agent
img
img
  1. 注意选择对应操作系统的教程。
img
img
  1. 往下滑动页面会看到 GitHub 给出的 Mac 下生成 SSH Key 的指南,按照指南的步骤一步一步进行。
img
img
  1. 打开终端(Terminal),复制粘贴以下文本到终端,把 your_email@example.com 替换成你注册 GitHub 时使用的邮箱,然后按下Enter键。
ssh-keygen -t ed25519 -C "your_email@example.com"
img
img
  • 如果你不记得注册 GitHub 时使用的邮箱,可以从 Settings 中的 Emails 中查看。
img
img
  1. 出现 Enter file in which to save the key(...) ,按下 Enter 键,一直按 Enter 直到出现以下画面。
img
img
  1. 🎉 恭喜你的 SSH Key 已经生成成功,接下来把生成的 SSH Key 添加到 ssh-agent。

添加 SSH Key 到 ssh-agent

  1. 在终端(Terminal)中输入命令:
eval "$(ssh-agent -s)"
  • 命令执行后终端会给出 Agent pid
  1. 如果你使用的是macOS Siera 10.12.2或以上的版本open in new window,你需要修改 ~/.ssh/config 文件来自动加载密钥到 ssh-agent 和储存 passphrases 到你的钥匙链。
  • 首先,检查电脑中是否存在 ~/.ssh/config 文件
open ~/.ssh/config
  • 如果像我一样显示这个 config 文件不存在,则创建这个文件
img
img
touch ~/.ssh/config	
  • 用编辑器打开 ~/.ssh/config 文件
nano ~/.ssh/config
  • 在 nano 窗口中复制粘贴以下代码:
Host *
	AddKeysToAgent yes
	UseKeychain yes
	IdentityFile ~/.ssh/id_ed25519
  • 粘贴代码后按 control+X 退出编辑器
img
img
  • 输入 y 保存更改
img
img
  • 出现这个画面后再按 Enter
img
img
  1. 将 SSH Key 添加到 ssh-agent。如果你使用的是Mac Monterey(12.0)及以上版本open in new window,请使用以下命令(因为在Mac Monterey(12.0)及以上版本中,-K 标志已经被废弃,被 --apple-use-keychain 代替)。
ssh-add --apple-use-keychain ~/.ssh/id_ed25519
  • 如果不是 Mac Monterey(12.0) 及以上版本,使用以下命令:
ssh-add -K ~/.ssh/id_ed25519
  • 🎉 出现 Identity added 即表示添加成功。
img
img

添加 SSH Key 到 GitHub

  1. 在终端输入以下命令, pbcopy 会复制 SSH Key 内容到剪贴板
pbcopy < ~/.ssh/id_ed25519.pub
  1. 再次打开 GitHub Settings 下的 SSH and GPG Key ,点击 New SSH key
img
img
  1. 添加本机生成的 SSH Key 到 GitHub:
  • Title 中给这个 SSH Key 命名
  • Key Type 选择 Authentication Key
  • KeyCommand+V 粘贴刚刚复制的 SSH Key
  • 添加后点击
img
img
  1. 🎉 添加完成。

测试 SSH Key 是否添加成功

  1. 选择一个要用 SSH Key clone 的仓库,复制这个仓库的 SSH 链接。
img
img
  1. 在终端输入:
git clone [ssh-url]
img
img
  1. 🎉 clone 成功即代表 SSH Key 添加成功。

Reference

欢迎关注我公众号:AI悦创,有更多更好玩的等你发现!

公众号:AI悦创【二维码】

AI悦创·编程一对一

AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Linux、」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh

C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh

方法一:QQopen in new window

方法二:微信:Jiabcdefh

上次编辑于:
贡献者: AI悦创,AndersonHJB
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度