生成 SSH 密钥

阿里云产品限时红包,最高 ¥1888 元,立即领取

生成 SSH 密钥

Git 仓库可以通过 git:// 来访问,目前类似 Github,Gitcafe,Coding等基于 Git 的托管服务都提供有配置 SSH 密钥,来访问托管仓库的功能。本文中将通过为 Github 账号配置 SSH 密钥来访问仓库为例,说明 SSH 密钥配置过程。

SSH 密钥是用于识别信任的电脑的一种方式,可以免去输入密码。下面的步骤将带你生成一个 SSH 密钥,并将其添加到你的 Github 账号。

步骤1:检查 SSH 密钥

首先,需要检查电脑上是否有已经存在的 SSH 密钥。打开终端并输入:

1
2
$ ls -al ~/.ssh
# Lists the files in your .ssh directory, if they exist

查看文件夹中列出的文件中是否已经有 SSH 公钥。默认情况下,公钥的文件名会是下面中的一个:

1
2
3
4
> id_dsa.pub
> id_ecdsa.pub
> id_ed25519.pub
> id_rsa.pub

如果你看到列出的文件已经存在一对公钥和私钥(如:id_rsa.pub 和 id_rsa),而你打算用来连接 Github,那么可以跳过步骤2,直接查看步骤3。

提示:如果你收到一个 ~/.ssh 不存在的错误,别担心,我们在步骤2中将创建它。

步骤2:生成新的 SSH 密钥

1、继续打开终端,复制并粘贴下面的文本。确保用你的 Github 邮箱替换掉其中的地址。

1
2
3
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# Creates a new ssh key, using the provided email as a label
# Generating public/private rsa key pair.

2、强烈建议保持默认设置,因此你在被提示”输入文件以保存密钥”时,直接按回车继续:

1
Enter file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

3、提示输入口令:

1
2
Enter passphrase (empty for no passphrase): [Type a passphrase]
# Enter same passphrase again: [Type passphrase again]

4、输口令以后,你将得到一个 SSH 密钥的指纹或者ID。看起来像这样:

1
2
3
4
Your identification has been saved in /Users/you/.ssh/id_rsa.
# Your public key has been saved in /Users/you/.ssh/id_rsa.pub.
# The key fingerprint is:
# 01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db your_email@example.com

步骤3:添加密钥到 ssh-agent

配置 ssh-agent 程序来使用 SSH 密钥,可以避免每次被提示输入口令:

1、确保 ssh-agent 是可用的:

1
2
3
# start the ssh-agent in the background
eval "$(ssh-agent -s)"
# Agent pid 59566

2、添加密钥到 ssh-agent

1
$ ssh-add ~/.ssh/id_rsa

提示:如果你在步骤2中没有生成新的 SSH 密钥,而是使用已经存在的密钥,那你需要替换上面命令中的 id_rsa 为你已经存在的私钥文件的名称。

步骤4:添加 SSH 密钥到你的账号

配置你的 Github 账号来使用 SSH 密钥:

复制 SSH 密钥到剪贴板,记住你可能将密钥命名为 id_dsa.pub, id_ecdsa.pub 或者 id_ed25519.pub,那么需要修改下列命令中的文件名:

1
2
pbcopy < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard

提示:也可以直接用文本编辑器等打开公钥文件,然后复制其中的内容。

警告:在复制过程中一定不能添加任何新行或者空格。

添加复制的密钥到 Github:

1、找到账户管理,点击其中的“设置”。

2、找到 SSH 密钥,点击添加 SSH 密钥。

3、在标题输入框中添加新密钥的描述文本。例如,如果你在使用个人的 Mac,可以设置密钥名称为 “Personal MacBook Air”。

4、在密钥输入框中粘贴刚才复制的密钥。

5、点击添加。

6、输入 Github 账号密码来确认。

步骤5:测试连接

为了确保一切工作正常,接下来将 SSH 到 Github。这么做的时候,你需要使用密码来验证。这个密码就是你之前创建的 SSH 密钥的口令。

1、打开终端并输入:

1
2
$ ssh -T git@github.com
# Attempts to ssh to GitHub

2、第一次你将看到下面的警告:

1
2
3
The authenticity of host 'github.com (207.97.227.239)' 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)?

核实你看到的消息中的指纹,并输入: yes

1
2
Hi username! You've successfully authenticated, but GitHub does not
# provide shell access.

3、如果出现上面的信息,并且用户是你 ,那么你的 SSH 密钥就安装成功了。如果你收到了关于 access denied 的消息,那么就是失败了,那么请确认前面的步骤,重新来过。

以上为 Mac 平台生成 SSH 密钥的步骤,Windows、Linux 平台略有不同。

原文链接:Generating SSH keys