创建新的SSH密钥,并添加到ssh-agent
创建密钥1
ssh-keygen -t rsa -b 4096 -C "[email protected]"
输入保存密钥的绝对路径和文件名,如/Users/Steve/.ssh/new_id_rsa
1
Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]
两次输入确认密钥的密码1
2Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
把密钥添加到ssh-agent
把ssh-agent在后台启动1
eval "$(ssh-agent -s)"
配置~/.ssh/config
文件,如果没有该文件,通过touch config
命令创建。注意HostName github.com
1
2
3
4
5Host github.com
HostName github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/new_id_rsa
把私钥添加到ssh-agent并存入keychain,执行命令会要求你输入密码1
ssh-add -K ~/.ssh/new_id_rsa
添加SSH公钥到你的GitHub账户
把公钥复制到剪贴板1
pbcopy < ~/.ssh/new_id_rsa.pub
进入Github账户找到Settings
,点击进入后选择SSH and GPG keys
,点击New SSH key
。在Title
框内填入标题,在框粘贴刚才复制的公钥。最后点击
Add SSH key
。
测试命令1
ssh -T [email protected]
如果有两个GitHub账户,如何配置SSH密钥并使用?
假设现在有两个GitHub账户,对应两个SSH密钥old_id_rsa和new_id_rsa。如果还没有密钥,分别按上面的步骤创建和添加。
修改config文件如下1
2
3
4
5
6
7
8
9
10
11Host old.github.com
HostName github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/old_id_rsa
Host new.github.com
HostName github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/new_id_rsa
测试old.github.com1
ssh -T [email protected]
测试new.github.com1
ssh -T [email protected]
如果报错了,可以使用下面命令查看详细的报错信息1
ssh -vT [email protected]
使用需要注意,git@
后要改为对应账户的别名。
如new_id_rsa密钥对应的GitHub账户上有个仓库test.git,且你的GitHub用户名是username,使用下面命令克隆1
git clone [email protected]:username/test.git
如old_id_rsa密钥对应的GitHub账户上有个仓库test.git,且你的GitHub用户名是oldman,使用下面命令克隆1
git clone [email protected]:oldman/test.git
避免git错用密钥,把git全局的用户名和邮箱删除1
2git config --global --unset user.email
git config --global --unset user.name
删除后,以后进入每个仓库都要指定该仓库局部的user.mail和user.name。
1 | git config user.email "[email protected]" |
参考
Connecting to GitHub with SSH
Generating a new SSH key and adding it to the ssh-agent
Adding a new SSH key to your GitHub account
Multiple GitHub Accounts & SSH Config