版本控制:GitHub 使用 SSH 密钥密码

My GitHub Home Page

参考:

  • https://help.github.com/cn/articles/connecting-to-github-with-ssh
  • https://blog.csdn.net/u013778905/article/details/83501204

关于 SSH 密钥

一般,在 Intellij IDEA 或 Eclipse 这些 IDE 中,通过设置 GitHub 的账号和密码,就可以正常使用了。如果更改了 GitHub 密码,按照 IDE 的提示重新设置即可。这里有个问题,一旦离职,或者更换新电脑,如果忘记在 IDE 上进行账号移除操作,容易引起不必要的麻烦,挽救措施就只有重新设置 GitHub 密码了。

通过使用 SSH 协议,只需要为每台电脑生成一个 SSH 密钥,并将 SSH 密钥添加到 GitHub 帐户即可,不再使用的 SSH 密钥随时可以通过 GitHub 帐户移除,这就变被动为主动了。

步骤如下:

  • 打开 Git Bash。
  • 检查现有 SSH 密钥
  • 生成新 SSH 密钥(如有 SSH 密钥,可跳过)
  • 将 SSH 密钥添加到 GitHub 帐户
  • 测试 SSH 链接

检查现有 SSH 密钥

$ ls -al ~/.ssh
total 16
drwxr-xr-x 1 Lewis 197121 0 8月   8 15:35 ./
drwxr-xr-x 1 Lewis 197121 0 7月  31 09:42 ../

默认情况下,公钥的文件名是以下之一:

  • id_dsa.pub
  • id_ecdsa.pub
  • id_ed25519.pub
  • id_rsa.pub

生成新 SSH 密钥

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Lewis/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
......

文件名和安全密码均可按回车,回车则采用默认的文件名和空的安全密码

将 SSH 密钥添加到 GitHub 帐户

  • 将 SSH 密钥复制到剪贴板。
$ clip < ~/.ssh/id_rsa.pub
  • 进入 https://github.com/settings/keys
  • 选择 New SSH key,填写 title,并粘贴 key,点击 Add SSH key
  • 按提示输入 GitHub 密码即可。

title 要有辨识度,方便管理,例如:[公司]-笔记本,[公司]-台式机,[个人]-笔记本。

测试 SSH 链接

$ ssh -T git@github.com

您可能会看到类似如下的警告:

The authenticity of host 'github.com (IP ADDRESS)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)?

或类似如下:

The authenticity of host 'github.com (IP ADDRESS)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)?

输入 yes

Warning: Permanently added 'github.com,xxx.xxx.xxx.xxx' (RSA) to the list of known hosts.
Hi username! You've successfully authenticated, but GitHub does not provide shell access.