同时配置多套sshkey授权不同的代码仓库

2021-12-14 22:16:54代码块, ssh, githubgit

1, 在 ~/.ssh 下创建一个文件:~/.ssh/config (windows系统中在C:/users/xxx/.ssh/)

把下面代码贴到config文件中

Host aa.github.com
	HostName github.com  # 仓库网站入口主域名
	IdentityFile ~/.ssh/id_rsa_aa # 密钥地址
	Port 7999 # 默认是22,如果端口不是22的,一定要配置: ssh://git@aa.github.com:7999/xx/xx.git

Host bb.github.com
	HostName github.com
	IdentityFile ~/.ssh/id_rsa_bb

注意事项:

1. Host 之后的属性,必须缩进,否则识别错误

2. Host 对应仓库中/.git/config中的 remote url

[remote "origin"] 
    url = git@aa.github.com:username/xx.git

3. HostName / IdentityFile 是必填项

扩展:修改git remote url

1, 通过命令修改:

git remote set-url origin git@aa.github.com:username/xx.git

2, 直接打开.git/config 文件进行修改

3,如果同一个username账号下的不同仓库,只需要配置一个密钥即可,不用多次配置:
比如配了如下密钥:

Host bb.github.com
	HostName github.com
	IdentityFile ~/.ssh/id_rsa_bb

可以同时用于以下仓库:

git@bb.github.com:username/a.git
git@bb.github.com:username/b.git
git@bb.github.com:username/c.git

只需要上面的host部分相同,就可以匹配到Host bb.github.com中的密钥id_rsa_bb