github使用SSH与客户端连接。如果是单用户(first user),生成密钥对后,将公钥保存至github, 每次连接时SSH客户端发送本地私钥(默认~/.ssh/id_rsa)到服务端验证。 单用户情况下,连接的服务器上保存的公钥和发送的私钥自然是配对的。
但是如果是多用户(first-user,second-user),我们在连接到second-user的帐号时, second-user的github空间里保存的是自己的公钥,但是SSH客户端依然发送默认的私钥,即first-user的私钥, 那么这个验证自然无法通过。 不过,要实现多帐号下的SSH key切换,只需在客户端(这里的“客户端”是linux vps. linux vps相对于github空间而言仍然是客户端。在Windows桌面系统上,git bash程序也是一个客户端)做一些配置即可。
首先cd到~/.ssh/,使用 ssh-keygen -t rsa生成新的SSH key:id_rsa_brightmann
(示例:
as3:~/.ssh# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (~/.ssh/id_rsa): ~/.ssh/id_rsa_brightmann
Enter same passphrase again:
Your identification has been saved in ~/.ssh/id_rsa_brightmann
Your public key has been saved in ~/.ssh/id_rsa_brightmann.pub)
生成完后,将新的SSH public key的内容添加到github。
完成以上步骤后在~/.ssh目录创建config文件,该文件用于配置私钥对应的服务器。内容如下:
配置完成后,在连接非默认帐号的github仓库时,远程库的地址要对应地做一些修改, 比如现在添加second帐号下的一个仓库origin,则需要这样添加:
git remote set-url origin git@github-second:briteming/briteming.github.io
而非原来的git remote set-url origin git@github.com:username2/username2.github.com
这样每次连接都会使用id_rsa_briteming与github服务器进行连接。至此,大功告成!
注意: github根据配置文件里的user email address来获取github帐号, 所以对于多帐号用户,一定要记得将user email address改为相应的email(second@mail.com)。
参考github帮助文档:
Manage multiple keys for different github repository
Introduction
ssh search ~/.ssh/id_rsa
by default, if you have multiple keys or your key’s name is not the
default, you should add the key into ssh-agent so that ssh can search
for it.
1 | eval "$(ssh-agent -s)" |
you can config ~/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
1 | Host * |
If github still ask you for password, you’re probably using the HTTPS clone URL for your repository. To solve it,
(1) Update the URL of origin remote using SSH instead of HTTPS
1 | git remote set-url origin git@github.com:username/repo.git |
(2) Make Git store the username and password and it will never ask for them.
1 | git config --global credential.helper store |
Calculate fingerprint from RSA keys
1 | ssh-keygen -lf ~/.ssh/id_rsa.pub |
In newer versions of OpenSSH, Base64 encoded SHA-256 is shown instead of hexadecimal MD5. To show the legacy style hash, use
1 | ssh-keygen -l -E md5 -f ~/.ssh/id_rsa.pub |