如何在一台设备上使用多个GitHub账户

为不同GitHub账户创建不同的SSH密钥

首先确保当前目录为.ssh

1
$ cd ~/.ssh

生成不同GitHub账户对应的ssh密钥

1
2
3
4
$ 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

1
2
3
> Enter passphrase (empty for no passphrase): [Type a passphrase]
>
> Enter same passphrase again: [Type passphrase again]

添加密钥到ssh-agent

1
2
$ ssh-add [--apple-use-keychain] ~/.ssh/github-username
# The --apple-use-keychain option is in Apple's standard version of ssh-add. In MacOS versions prior to Monterey (12.0), the --apple-use-keychain and --apple-load-keychain flags used the syntax -K and -A, respectively.

添加公钥至GitHub

  1. 将公钥内容复制到剪切板

    1
    $ pbcopy < ~/.ssh/github-username.pub

  2. 粘贴到GitHub

    • Settings > SSH and GPG keys > New SSH Key
    • 填写title并粘贴公钥

配置ssh config

打开~/.ssh/config

1
2
3
4
5
6
7
8
9
10
11
# 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

测试连接

1
2
$ ssh -T git@github.com
$ ssh -T git@github.com-another-github-username

正常情况将会看到👇

1
2
> 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.

如何使用

1
2
$ 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.emailuser.name

1
2
$ 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


如何在一台设备上使用多个GitHub账户
http://example.com/2023/02/25/multiple-GitHub-accounts-on-a-single-machine/
作者
臣皮蛋
发布于
2023年2月25日
许可协议