Pages

Thursday, 26 April 2012

多个github帐号的SSH key切换

多个github帐号的SSH key切换

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 passphrase (empty for no passphrase):
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文件,该文件用于配置私钥对应的服务器。内容如下:
12799@DESKTOP-B6LK9IO MINGW64 ~/.ssh (main)
$ cat config
# first user(brightmann@gmail.com)
Host github-first
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_brightmann

# second user(briteming@gmail.com)
Host github-second
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_briteming

# third user(ymbrite@gmail.com)
Host github-third
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_ymbrite

# fourth user(luckypoem@gmail.com)
Host github-fourth
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_luckypoem

12799@DESKTOP-B6LK9IO MINGW64 ~/.ssh (main)
$ ls
config             id_rsa_luckypoem          id_rsa_ymbrite
id_rsa_brightmann     id_rsa_briteming   
known_hosts

12799@DESKTOP-B6LK9IO MINGW64 ~/.ssh (main)
$

配置完成后,在连接非默认帐号的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
(然后,运行git push origin master就不会遇到错误了

这样每次连接都会使用id_rsa_briteming与github服务器进行连接。至此,大功告成!

注意: github根据配置文件里的user email address来获取github帐号, 所以对于多帐号用户,一定要记得将user email address改为相应的email(second@mail.com)。

参考github帮助文档:
https://github.com/settings/keys
https://docs.github.com/en/authentication/connecting-to-github-with-ssh
https://docs.github.com/en/authentication/troubleshooting-ssh
不错,按此文我操作成功。
-------------------------------------------------------------------------------------------