Git之SSH密钥实现免密码

SSH密钥用于免密码git操作时验证信任的客户端。下面将说一下生成SSH密钥和将SSH密钥添加到对应git账户(不特指github,其他平台也可以如coding)的步骤。

本文以mac osx系统为例。

检查

检查是否存在SSH密钥

首先,我们应该检查一下计算机中是否已经存在SSH密钥,打开终端输入:

$ ls -al ~/.ssh
# 如果有文件存在,列出.ssh文件夹下的文件

默认会有以下文件:

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

注:

  • 如果已经存在了SSH公钥和私钥,可以直接跳过第二、三步。
  • 如果出现错误~/.ssh doesn't exist,不用担心,只需要在~目录下创建.ssh目录即可mkdir ~/.ssh

生成新的SSH密钥

ssh-keygen

在终端中执行一下命令,把邮箱换成自己的邮箱即可

$ 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.

一路回车

Github官方强烈建议保持默认设置,所以下面出现的三个需要输入的时候,直接回车就好:

$ Enter file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]
$ Enter passphrase (empty for no passphrase): [Type a passphrase]
$ Enter same passphrase again: [Type passphrase again]

结果

成功完成上述操作后,就会出现下面类似的样子:

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

向ssh-agent中添加SSH密钥

验证ssh-agent可用

确保ssh-agent是可用的:

# start the ssh-agent in the background
$ eval "$(ssh-agent -s)"
# Agent pid 43686

添加SSH密钥

将ssh密钥添加到ssh-agent中:

$ ssh-add ~/.ssh/id_rsa

git账户添加SSH密钥

首先执行下面命令,将刚生成的SSH密钥拷贝到系统粘贴板:

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

注:

可以自己到HOME的.ssh目录下拷贝is_rsa.pub的内容,但一定注意不要有新行或空格,上述命令方式比较安全!

以github为例讲解向账户中添加SSH密钥,coding是类似的。

进入settings

点击自己github首页右上角的头像,选择settings(设置)

1

选择SSH Keys

在左边栏用户设置中选择SSH Keys

2

添加SSH

点击右上角的Add SSH Key

3

输入SSH密钥

在下面跳出的输入框中分别输入用于区分SSH密钥的名称和贴入已经复制到系统粘贴板上的SSH密钥:

4

添加即可

点击5,然后输入账户密码完成添加。

测试SSH连接

为了确保我们之前做的一切都是可用的,现在可以尝试SSH连接Github。

ssh -T

打开终端,输入命令:

$ ssh -T git@github.com

警告

可能会看到下面的警告:

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继续:

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

注意

如果上面的用户名是你的,就说明已经把SSH密钥绑定好了,以后可以用ssh免密码进行git推送了。

参考:


gitssh

1021 字

2015-11-02 04:00 +0000