第 1 步:为每个账号生成独立的 SSH 密钥
假设你有两个账号:
- 个人账号: personal@example.com
- 公司账号: company@example.com
- 为个人账号生成密钥 :
打开终端(或 Git Bash),执行以下命令。注意 -f 参数指定了密钥文件的名称, -C 参数是注释(一般用邮箱)。
ssh-keygen -t ed25519 -C "personal@example.com" -f ~/.ssh/id_ed25519_personal
* 当提示“Enter passphrase”时,**强烈提议设置一个密码**,增加安全性。
#技术分享
* 这会生成两个文件:`~/.ssh/id_ed25519_personal`(私钥)和 `~/.ssh/id_ed25519_personal.pub`(公钥)。
- 为公司账号生成密钥 :
同样,执行命令生成另一对密钥。
ssh-keygen -t ed25519 -C "company@example.com" -f ~/.ssh/id_ed25519_company
* 这会生成:`~/.ssh/id_ed25519_company`(私钥)和 `~/.ssh/id_ed25519_company.pub`(公钥)。
第 2 步:将公钥添加到对应的 GitHub 账号
- 复制个人账号的公钥 :
pbcopy < ~/.ssh/id_ed25519_personal.pub
clip < ~/.ssh/id_ed25519_personal.pub
cat ~/.ssh/id_ed25519_personal.pub
然后登录你的**个人 GitHub 账号**,进入 `Settings -> SSH and GPG keys`,点击 `New SSH key`,粘贴公钥内容。
- 复制公司账号的公钥 :
pbcopy < ~/.ssh/id_ed25519_company.pub
clip < ~/.ssh/id_ed25519_company.pub
cat ~/.ssh/id_ed25519_company.pub
登录你的**公司 GitHub 账号**,重复上述步骤,添加公钥。
第 3 步:创建并配置 SSH Config 文件
这是整个方案的 核心 !这个文件会告知 SSH 客户端如何根据域名匹配不同的密钥。
- 创建或编辑 ~/.ssh/config 文件(如果文件不存在,直接新建)。
- 在文件中添加以下内容:
Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
IdentitiesOnly yes
Host github.com-company HostName github.com User git IdentityFile ~/.ssh/id_ed25519_company IdentitiesOnly yes
**配置解释**:
* `Host github.com-personal`:这是一个**别名**。当你使用这个别名时,会应用下面的配置。
* `HostName github.com`:真实的域名是 `github.com`。
* `User git`:登录用户名是 `git`(GitHub SSH 协议固定为 git)。
* `IdentityFile ~/.ssh/id_ed25519_personal`:指定使用哪个私钥文件。
* `IdentitiesOnly yes`:强制 SSH 只使用 `IdentityFile` 指定的密钥,防止默认使用其他密钥导致认证失败。
第 4 步:克隆仓库并配置本地用户信息
目前,克隆仓库的方式需要稍作改变。
- 克隆个人仓库 :
原始的克隆地址是 git@github.com:personal-username/my-repo.git 。
你需要将其中的 github.com 替换为你配置的别名 github.com-personal :
git clone git@github.com-personal:personal-username/my-repo.git
- 克隆公司仓库 :
同理,使用 github.com-company 别名:
git clone git@github.com-company:company-username/work-repo.git
- 进入仓库目录,配置本地用户信息 :
这一步至关重大!它决定了你的 git commit 提交记录关联到哪个用户。
cd my-repo
git config user.name "Your Personal Name"
git config user.email "personal@example.com"
cd ../work-repo git config user.name "Your Company Name" git config user.email "company@example.com"
**注意**:这里使用的是 `git config`(不带 `--global`),表明该配置**仅对当前仓库有效**。
第 5 步:测试连接
ssh -T git@github.com-personal
ssh -T git@github.com-company
如果都看到成功提示,祝贺你,配置完成!后来在这些仓库里进行 git push 、git pull 都会自动使用正确的账号。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



