本文最后更新于 676 天前,其中的信息可能已经有所发展或是发生改变。
为不同GitHub账户创建不同的SSH密钥
首先确保当前目录为.ssh
$ cd ~/.ssh
生成不同GitHub账户对应的ssh密钥
$ ssh-keygen -t ed25519 -C "your_email@example.com" -f "github-username"
# If you are using a legacy system that doesn't support the Ed25519 algorithm, use:
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f "github-username"
-C stands for comment to help identify your ssh key
-f stands for the file name where your ssh key get saved
> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]
添加密钥到ssh-agent
$ ssh-add ~/.ssh/github-username
添加公钥至GitHub
- 将公钥内容复制到剪切板
$ pbcopy < ~/.ssh/github-username.pub
- 粘贴到GitHub
- Settings > SSH and GPG keys > New SSH Key
- 填写title并粘贴公钥
配置ssh config
打开~/.ssh/config
# Default github account: github-username
Host github.com
HostName github.com
IdentityFile ~/.ssh/github-username
IdentitiesOnly yes
# Other github account: another-github-username
Host github-another-github-username
HostName github.com
IdentityFile ~/.ssh/another-github-username
IdentitiesOnly yes
测试连接
$ ssh -T git@github.com
$ ssh -T git@github.com-another-github-username
正常情况将会看到👇
> Hi github-username! You've successfully authenticated, but GitHub does not provide shell access.
> Hi another-github-username! You've successfully authenticated, but GitHub does not provide shell access.
如何使用
$ git clone git@github.com-{your-username}:{owner-user-name}/{the-repo-name}.git
# [e.g.] git clone git@github.com-github-username:github-username/TestRepo.git
为了确保使用正确的账号进行commits和push,需要在每个仓库配置user.email和user.name
$ git config user.email "your_email@example.com"
$ git config user.name "github username"
参考
How To Work With Multiple Github Accounts on a single Machine
Generating a new SSH key and adding it to the ssh-agent
Using multiple github accounts with ssh keys