参考自https://help.github.com/articles/generating-ssh-keys/
亲自在Mac OS和cent OS中测试成功,命令均一样。
SSH keys可以无需密码进行github更新,每台电脑均需要生成唯一的SSH并添加到github个人资料的settings中。
centOS需要使用命令sudo yum install git安装git。
Step 1: 检查SSH keys
首先我们需要检测系统是否已经存在SSH keys,可以使用终端输入下列的命令:
ls -al ~/.ssh # Lists the files in your .ssh directory, if they exist
如果存在,可以看到如下的列表:
- id_dsa.pub
- id_ecdsa.pub
- id_ed25519.pub
- id_rsa.pub
如果想使用现有的SSH keys,可以忽略步骤2和步骤3,如果没有现成的SSH keys,我们接下来会通过终端来生成。
Step 2: 生成SSH key
- 输入下面的命令,其中需要填写自己的邮箱:
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.
- 使用默认设置即可,直接按回车:
# 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
Step 3: 把生成的key添加到ssh-agent
ssh-agent是一种控制用来保存公钥身份验证所使用的私钥的程序,其实ssh-agent就是一个密钥管理器,原型ssh-agent以后,使用ssh-add将私钥交给ssh-agent保管,其他程序需要身份验证的时候可以自动将验证申请交给ssh-agent来完成整个认证过程。
- 先检查ssh-agent是否在运行:
# start the ssh-agent in the background eval "$(ssh-agent -s)" # Agent pid 59566
- 把SSH key添加ssh-agent:
ssh-add ~/.ssh/id_rsa
注意:如果你采用现有的SSH keys,你需要把id_rsa(这是一个文件名)替换成现有的私钥文件名。
如果出现
-
Could not open a connection to your authentication agent.
需要先执行下面的命令,才能进行ssh-add操作
ssh-agent bash
Step 4: 把SSH key添加到github账户
这个时候需要复制id_rsa.pub的内容,即SSH key,注意这个文件不一定是id_rsa.pub,有可能是id_dsa.pub
,id_ecdsa.pub
or id_ed25519,需要看自己的设置。
pbcopy < ~/.ssh/id_rsa.pub # Copies the contents of the id_rsa.pub file to your clipboard
如果pbcopy失败,可以直接用vi打开id_rsa.pub复制里面的内容。
详细步骤:
进入个人账户的Settings.
选择SSH keys.
点击Add SSH key.
- 添加title,题目可为 “Personal MacBook Air”,根据自己的情况添加。
复制key.
点击Add key.
- 最后会要求输入github的密码进行确认.
Step 5: 测试连接
在完成上述步骤后,可以测试连接,确保ssh正常工作。在尝试ssh连接时,github会提示认证。
- 打开终端并输入:
ssh -T git@github.com # Attempts to ssh to GitHub
- 然后会看到下面的警告:
# 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连接到github!
If you receive a message about “access denied,” you can read these instructions for diagnosing the issue.
If you’re switching from HTTPS to SSH, you’ll now need to update your remote repository URLs. For more information, see Changing a remote’s URL.