背景
当有多个 git 账号时,比如:
- 一个 gitee,用于公司内部的工作开发;
- 一个 github,用于自己进行一些开发活动;
默认只会用 ~/.ssh/id_rsa,需要为不同 Host 指定不同私钥。
操作步骤
1、为每个账号生成独立的 SSH-Key
ssh-keygen -t rsa -C 'xxxxx@company.com' -f ~/.ssh/gitee_id_rsa
ssh-keygen -t rsa -C 'xxxxx@qq.com' -f ~/.ssh/github_id_rsa
ssh-keygen -t rsa -C 'xxxxx@qq.com' -f ~/.ssh/git_company_id_rsa
2、新建 ~/.ssh/config
Host 和 HostName 填 git 服务器域名,IdentityFile 指定私钥路径:
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitee_id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
# bitbucket.org
Host bitbucket.org
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
# git.company.com
Host git.company.com
HostName git.company.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/git_company_id_rsa
3、逐个测试连通性
ssh -T git@gitee.com
ssh -T git@github.com
ssh -T git@bitbucket.org
ssh -T git@git.company.com
成功时的返回:
Hi ****! You've successfully authenticated, but GITEE.COM does not provide shell access.
如果私钥设置了 passphrase,会先提示输入:
Enter passphrase for key '/Users/***/.ssh/github_id_rsa':
Hi ****! You've successfully authenticated, but GitHub does not provide shell access.
补充
- 把对应的
.pub文件内容添加到各平台的 SSH Keys 设置中; - 同一 Host 需要区分多个账号时,可以用
Host别名(如github-work)配合HostName github.com,克隆时把域名换成别名即可。