Git管理多个远程仓库账号,如Github

125 阅读2分钟

当在一台电脑上需要使用多个Github时,总是需要重置配置,很麻烦。

使用SSH Keys可以根据填写的ssh的url地址来配对是哪个账号的仓库,从而不需要重新配置Git信息。

实现

1、先配置本地SSH Keys:

·    ​查看本机Git是否存在SSH Keys

任意地方右键 打开Git bash,并输入指令

cd ~/.ssh

要是显示 No such file or directory 就输入指令

ssh-keygen -t rsa -C "your_email@example.com"

或者根据 GitHub文档 参考链接①:输入

ssh-keygen -t ed25519 -C "your_email@example.com"

其中 your_email@example.com 为你的GitHub绑定的邮箱。

根据提示输入想要生成密钥文件的名字(也可以空着,之

后再改)。

再根据提示输入两次密码(在用密钥管理仓库时使用,也可以为空)。

完成后会在 C:\Users\(自己电脑的用户名)\  下生成 .ssh文件及公私钥。

参考GitHub文档 链接① 复制公钥

输入指令,复制公钥(公钥文件后缀为.pub)

clip <~/.ssh/1234.pub

2、添加公钥到远程仓库:

进入GitHub的 SSH and GPU keys 增加新公钥。

在key里粘贴,刚复制的公钥,然后输入自定义Title。按增加。

添加成功。

3、测试是否能连接成功:

    ​    输入指令测试连接:

ssh -T git@github.com

显示 “Hi  ..., You've sucessfully...”及成功连接。

注意:有时会显示 “ssh: connect to host github.com port 22: Connection refused”

此时需要在 .ssh里的config文件里 添加指令。

· 若是不存在config文件,先输入命令生成文件

touch ~/.ssh/config

· 打开文件并输入

Host github.com
  Hostname ssh.github.com
  Port 443

保存,后再次按3步骤来输入代码来测试连接。

4、配置多个账号:

按照1,2,3步骤创建另一个账号的公私钥, 注意文件名字不用一样,否则会覆盖)。

**
**

在config文件里输入:

Host github-firstAccount
	Hostname ssh.github.com
	Port 443
Host github-secondAccount
	Hostname ssh.github.com
	Port 443
#Default GitHub
Host github-firstAccount
  HostName github.com
  User git
  IdentityFile ~/.ssh/FirstKey
Host github-secondAccount
  HostName github.com
  User git
  IdentityFile ~/.ssh/SecondKey

其中 FirstKey为第一个账号的私钥文件(与你复制的公钥文件同名文件),SecondKey为第二个账号私钥文件。

5、使用:

使用时复制仓库的SSH链接:

在git bash输入指令克隆,将ssh链接中的@github.com换成@ (你在config文件里Host 后面的字符串) ,如:

 

git clone git@github-secondAccount:Company/testing.git

参考链接① Github文档(生成公私钥):

https://docs.github.com/zh/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

参考② GitHub文档(配置多个账号):

https://github.com/xiaofuzi/xiaofuzi.github.com/issues/5

③ 配置ssh key:

https://blog.csdn.net/weixin_42310154/article/details/118340458

④配置ssh key:

https://blog.csdn.net/ITWANGBOIT/article/details/103624503

⑤ Git Bash中把文件内容复制到剪贴板的命令:

https://www.cnblogs.com/flipped/p/6654498.html