使用ssh key的方式建立和git服务器的通信

1.以前大家好像都在用https的方式同git来同步代码,但是到了新公司后,主管说要配ssh key,所以大概了解一下

  An SSH key allows you to establish a secure connection between your computer and GitLab(or github).

   ssh key就是为了让两个机器之间使用ssh不需要用户名和密码。具体实现的原理是 因为git可以在本机保存一个私钥,然后在git服务器上面填写你自己的公钥,这样你在使用git的命令更新代码或者提交代码的时候,git服务器就会自动的通过公钥和私钥来验证客户机的身份,达到免输入用户名和密码的目的。下面介绍一下生成公私钥的步骤

2.步骤

  • 检查SSH keys是否存在
  • 生成新的ssh key
  • 将ssh key添加到GitHub中

1. 检查SSH keys是否存在

  输入下面的命令,如果有文件id_rsa.pub 或 id_dsa.pub,则直接进入步骤3将SSH key添加到GitHub中,否则进入第二步生成SSH key

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

  或者通过下面的命令直接查看本地是否已经有了这个文件

cat ~/.ssh/id_rsa.pub

  如果你能看到一长串以ssh-rsa或者ssh-dsa开头的字符,那么证明你的本地已经有了ssh可以了

2. 生成新的ssh key

第一步:生成public/private rsa key pair
在命令行中输入ssh-keygen -t rsa -C "your_email@example.com"

默认会在相应路径下(/your_home_path)生成id_rsaid_rsa.pub两个文件,如下面代码所示

ssh-keygen -t rsa -C "your_email@example.com"
# Creates a new ssh key using the provided email
Generating public/private rsa key pair.
#This command will prompt you for a location and filename to store the key
pair and for a password. When prompted for the location and filename, you
can press enter to use the default.
Enter file in which to save the key (/your_home_path/.ssh/id_rsa):

第二步:输入passphrase(本步骤可以跳过)

设置passphrase后,进行版本控制时,每次与GitHub通信都会要求输入passphrase,以避免某些“失误”

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

sample result:

Your identification has been saved in /your_home_path/.ssh/id_rsa.
Your public key has been saved in /your_home_path/.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

第三步:将新生成的key添加到ssh-agent中:

上面的命令就可以生成ssh key并保存在你本地

Please copy the complete key starting with ssh- and ending with your username and host.

To copy your public key to the clipboard, use code below. Depending on your OS you'll need to use a different command:

Windows:

clip < ~/.ssh/id_rsa.pub

Mac:

pbcopy < ~/.ssh/id_rsa.pub

GNU/Linux (requires xclip):

xclip -sel clip < ~/.ssh/id_rsa.pub

3. 将ssh key添加到GitHub中

用自己喜欢的文本编辑器打开id_rsa.pub文件,里面的信息即为SSH key,将这些信息复制到GitHub的Add SSH key页面即可

不同的操作系统,均有一些命令,直接将SSH key从文件拷贝到粘贴板中,如下:

mac

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

windows

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

linux

sudo apt-get install xclip
# Downloads and installs xclip. If you don't have `apt-get`, you might need to use another installer (like `yum`)

xclip -sel clip < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard

将ssh key的公钥添加到github或者gitlib的ssh 标签下面就可以了

 

posted on 2016-08-10 17:27  行殇  阅读(1606)  评论(0编辑  收藏  举报

导航