起因
私有仓库可以使用 Deploy Keys 来使得在不需要在一台机器上放置自己的 GitHub 私钥来保持对仅仅一个仓库的使用权限,但是如果需要连接到许多的私有仓库的时候,如果提交的都是同一个密钥对,那么 GitHub 会提示
Key is already in use
,也就是需要添加不同的密钥对ssh-agent
可以在添加了多个密钥对之后,使用 ssh-agent 来管理多个私钥
启动 ssh-agent
ssh-agent 一般需要手动启动
eval `ssh-agent`
启动之后,可以检查环境变量来确定是否配置正确
echo $SSH_AGENT_SOCK
添加私钥
ssh-add /path/to/private/key
如果没有指定路径,会把默认的几个位置上的私钥都添加了,包括
~/.ssh/id_rsa
、.ssh/id_dsa
、~/.ssh/id_ecdsa
、~/.ssh/id_ed25519
和 ~/.ssh/identity
可以使用如下的命令来列出添加好的私钥
ssh-add -l
ssh config
但是 ssh-agent 也不一定会一直运行着,而且对于 wsl 用户,ssh-agent 有些不太友好,可以添加不同的 config 来实现
git 通过 ssh 的方式来 clone 的时候,会检查
~/.ssh/config
的配置,比如 git@
github.com
:github/docs
就会检查 Host 为 github.com
的配置。但是我们有多个repo的时候,公用的是同一个 domain,即 github。因此即使在 config 里面添加了 IdentityFile,也不能使得不同的 repo 使用不同的密钥对。但是,可以在 github.com 前面添加子域名来进行辨别,并且不会影响 git 的使用。即,可以使用
repo1.github
作为第一个 repo 的域名, repo2.github
作为第二个 repo 的域名可以得到配置文件如下
Host repo1.github
HostName github.com
User git
IdentityFile /home/elsa/.ssh/repo1.github.id_ecdsa
IdentitiesOnly yes
Host repo2.github
HostName github.com
User git
IdentityFile /home/elsa/.ssh/repo2.github.id_ecdsa
IdentitiesOnly yes
使用
ssh -T
检查ssh -T git@repo1.github
会返回
Hi zeyugao/repo1! You've successfully authenticated, but GitHub does not provide shell access.
就说明认证成功了
使用
需要修改 clone 的时候的 url
git clone git@github.com:zeyugao/repo1.git
修改为
git clone git@github.com:repo1.github/repo1.git
就可以正常使用了
如果是已经 clone 好的,可以修改 remote,或者直接改
.git/config
下面的 [remote "origin"]
[remote "origin"]
url = "ssh://git@repo1.github:elsa/repo1.git"