使用ssh key的方式創建和git服務器的通訊

1.之前你們好像都在用https的方式同git來同步代碼,可是到了新公司後,主管說要配ssh key,因此大概瞭解一下linux

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

   ssh key就是爲了讓兩個機器之間使用ssh不須要用戶名和密碼。具體實現的原理是 由於git能夠在本機保存一個私鑰,而後在git服務器上面填寫你本身的公鑰,這樣你在使用git的命令更新代碼或者提交代碼的時候,git服務器就會自動的經過公鑰和私鑰來驗證客戶機的身份,達到免輸入用戶名和密碼的目的。下面介紹一下生成公私鑰的步驟git

2.步驟github

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

1. 檢查SSH keys是否存在

  輸入下面的命令,若是有文件id_rsa.pub 或 id_dsa.pub,則直接進入步驟3將SSH key添加到GitHub中,不然進入第二步生成SSH keyshell

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

  或者經過下面的命令直接查看本地是否已經有了這個文件windows

cat ~/.ssh/id_rsa.pub

  若是你能看到一長串以ssh-rsa或者ssh-dsa開頭的字符,那麼證實你的本地已經有了ssh能夠了ruby

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

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,以免某些「失誤」ide

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 標籤下面就能夠了

相關文章
相關標籤/搜索