window系统通过ssh实现多账户同时使用

开启OpenSSH Authentication Agent

管理员身份打开Windows PowerShell,运行以下命令

1
2
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service -Name ssh-agent

然后执行ssh-add -l验证服务是否开启成功

生成密钥对

首先进入到ssh目录

1
cd ~/.ssh

然后执行以下命令生成密钥对

1
ssh-keygen -t rsa -b 4096 -C "[email protected]" -f id_rsa_account1
  • ~/.ssh/ 是密钥存放的默认目录(Windows 上对应 C:\Users\你的用户名.ssh\)。
  • id_rsa_account1 是你为这个密钥对指定的文件名。
  • your_email_account1@example.com 是你的备注,通常是你的邮箱。
  • 系统会提示你输入一个密码 (passphrase)。为了安全,强烈建议设置密码。
  • 为你的第二个账户重复此步骤,使用不同的文件名(例如 id_rsa_account2)

创建配置文件

创建或编辑 config 文件:

在 C:\Users\你的用户名.ssh\ 目录下创建一个名为 config 的文件(如果没有的话)。确保文件没有 .txt 后缀。
你可以使用任何文本编辑器,例如 VS Code、Notepad++,或者在 Git Bash 中使用 touch ~/.ssh/config 创建,然后用 notepad ~/.ssh/config 或 code ~/.ssh/config 打开。
添加配置内容:
为每个 Git 账户添加一个 Host 条目。使用一个易于识别的别名作为 Host。

示例 ~/.ssh/config 内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# account1
Host my-account1
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_account1
IdentitiesOnly yes

# account2
Host my-account2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_account2
IdentitiesOnly yes


配置github

首先需要复制你刚才生成好的公钥内容

1
cat ~/.ssh/id_rsa_account1.pub
  • 登录GitHub账户。进入 “Settings” (设置)。

  • 在左侧导航栏找到 “SSH and GPG keys” (SSH 和 GPG 密钥)。

  • 点击 “New SSH key” (新建 SSH 密钥) 或 “Add SSH key” (添加 SSH 密钥)。

  • 给你的密钥起一个标题 (Title),例如 “My Laptop” 或 “Work Computer”。

  • 将你刚才复制的公钥内容粘贴到 “Key” (密钥) 文本框中。

  • 点击 “Add SSH key” (添加 SSH 密钥)。

测试 SSH 连接

添加完公钥后,在你的终端测试一下 SSH 连接:

1
ssh -T git@my-account1

如果这个命令成功,并且提示 “Hi your-github-username! You’ve successfully authenticated…”, 那么说明针对这个别名的 SSH 配置和密钥是正确的。

修改远程url

使用 git remote set-url 命令,将 github.com 替换为你在 ~/.ssh/config 中定义的 Host 别名。

如果你希望使用账户1:

1
git remote set-url origin git@my-account1:your_github_username/your_repo.git