在单台计算机上设置多个 ssh 密钥和 git 存储库

在这个简短的指南中,将引导你在同一台计算机上使用 ssh 设置多个 GitHub 帐户,以便不同的存储库将自动与正确的 ssh 密钥和帐户相关联。

解释问题:
假设你有两个 GitHub 帐户 — 一个用于工作,另一个用于个人使用。
这些帐户中的每一个在你的计算机上都有一个或多个要与所述帐户关联的存储库。

第 1 步:设置 ssh

为每个帐户创建一个 ssh 密钥并将它们添加到你的 GitHub 帐户,你可以在此处使用 GitHub 的指南来了解如何执行此操作。

第 2 步:设置 ssh 配置主机。

在 .ssh 文件夹中创建一个 SSH 配置文件。此文件负责告诉你的 ssh 代理要为每个域使用什么密钥:

touch ~/.ssh/config

现在将以下内容添加到配置文件中:

Host github.com-personal-account # github.com-{name-with-hyphen}
  HostName github.com
  AddKeysToAgent yes
  UseKeychain yes # only if you used a keychain when creating the ssh key
  IdentityFile ~/.ssh/private_key_1

Host github.com-work-account
  HostName github.com 
  AddKeysToAgent yes
  UseKeychain yes # only if you used a keychain when creating the ssh key
  IdentityFile ~/.ssh/private_key_2

你应该能够使用以下命令测试此部分的成功/失败:

ssh -T git@github.com-personal-account

# If everything is working you should see this message: 
Hi {github account name}! Youve successfully authenticated, but GitHub does not provide shell access.

# if not - troubleshoot the previous steps before moving on :)

第 3 步:将存储库与相应的 ssh 密钥关联。

我们在这里可能会遇到两种不同的情况;
一个是克隆新存储库,第二个是附加已克隆的存储库。
这两种情况都非常简单,所以让我逐一解释一下。

克隆新存储库:
转到 GitHub 并按“<>代码”按钮,选择 ssh 并复制链接。
你将收到如下内容:(请遵循示例)

git@github.com:{repo-owner-name}/{repo-name}.git

# change it to:
git@github.com-{username-from-host-in-config}:{repo-owner-name}/{repo-name}.git

# example:
git@github.com-personal-account:{repo-owner-name}/{repo-name}.git

#now use it to run git clone:
git clone git@github.com-personal-account:{repo-owner-name}/{repo-name}.git

上面的命令将克隆仓库,并确保涉及此仓库的每个 git 命令都将通过相应的 ssh 密钥定向。

(不要忘记为你的提交元数据设置 and 属性)。user.nameuser.email

链接现有的本地仓库:
如果你已经有一个本地存储库,则可以轻松将其设置为与新设置的 ssh 一起使用。转到存储库基目录并执行以下命令:

#this command shows the current origin of the repo
git remote -v

#you will recieve something like this:
origin git@github.com:{repo-owner}/{repo-name}.git (fetch)
origin git@github.com:{repo-owner}/{repo-name}.git (push)

# copy the origin and add to it as follows:
git@github.com-{profile-name}:{repo-owner}/{repo-name}.git

# example:
git@github.com-personal-account:{repo-owner}/{repo-name}.git

# now use the origin you wrote to set the repo new origin 
git remote set-url origin git@github.com-personal-account:{repo-owner}/{repo-name}.git

就是这样,完成了。
你可以通过运行 git pull 来确保它正常工作。
(不要忘记为你的提交元数据设置 and 属性)。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹤冲天Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值