一台机器配置多个git账号并配置不同的 SSH 密钥

在一台机器上使用多个 Git 账号,并为每个账号配置不同的 SSH 密钥,是一种常见需求,尤其是在处理多个项目或在不同的组织中工作时。以下是设置的步骤:

1. 生成多个 SSH 密钥

首先,为每个 Git 账号生成一个新的 SSH 密钥。

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

在提示输入文件名时,为每个密钥指定一个唯一的名字,例如:

  • ~/.ssh/id_rsa_account1
  • ~/.ssh/id_rsa_account2

your_email@example.com 替换成与每个 Git 账号关联的电子邮件地址。

2. 将 SSH 密钥添加到 SSH 代理

对于每个生成的密钥,使用以下命令将它们添加到 SSH 代理中:

ssh-add ~/.ssh/id_rsa_account1
ssh-add ~/.ssh/id_rsa_account2

确保 SSH 代理正在运行(使用 eval "$(ssh-agent -s)" 启动)。

3. 为每个账号配置 SSH

创建或编辑 ~/.ssh/config 文件,为每个账号添加配置:

# Account 1
Host github.com-account1
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_account1

# Account 2
Host github.com-account2
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_account2

在这里,github.com-account1github.com-account2 是自定义别名,用于区分不同的 GitHub 账号。

4. 将 SSH 密钥添加到 GitHub 账号

对于每个 SSH 密钥,需要将它们分别添加到相应的 GitHub 账号中:

  • 在 GitHub 网站上,进入设置。
  • 转到“SSH and GPG keys”部分。
  • 选择“New SSH key”,粘贴你的 SSH 公钥内容,并保存。

5. 配置 Git 使用特定账号

当克隆仓库时,使用自定义的 Host 别名而不是实际的 github.com 域名。例如:

git clone git@github.com-account1:Username/Repository.git

其中,github.com-account1 对应于 ~/.ssh/config 文件中的 Host 别名。

6. 确保 Git 配置正确

根据你正在工作的仓库,确保 Git 的 user.nameuser.email 配置正确。可以在仓库目录中运行以下命令来设置:

git config user.name "Your Name"
git config user.email "your_email@example.com"

以上步骤将使你能够在一台机器上使用多个 Git 账号,每个账号都有其对应的 SSH 密钥。

退出移动版