要配置多个 SSH 密钥对,你可以按照以下步骤进行:
1. 生成新的 SSH 密钥对:
如果你还没有生成要添加的新 SSH 密钥对,请按照以下步骤生成:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f ~/.ssh/id_rsa_new
在命令中替换 your_email@example.com
为你的邮箱地址,并且 -f
选项可以指定生成的密钥对文件名,例如 id_rsa_new
。
2. 添加新的密钥对到 SSH 代理:
eval "$(ssh-agent -s)" #命令确保 ssh-agent 运行
ssh-add ~/.ssh/id_rsa_new
这会将新生成的 SSH 密钥添加到 SSH 代理中。
3. 将公钥添加到你的代码托管服务提供商:
在你的代码托管服务提供商(例如 GitHub、GitLab、Bitbucket 等)的网站上,导航到你的个人设置或账户设置页面,并添加你的新 SSH 公钥。
4. 配置 SSH 主机别名:
如果你需要为不同的代码仓库使用不同的密钥对,你可以编辑 ~/.ssh/config
文件,并配置每个主机的别名和对应的密钥。示例如下:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
Host github.com-x #别名(示例:git clone git@github.com-x:pineux/blog.git)
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_bitbucket
在这个示例中,github.com
使用默认的 ~/.ssh/id_rsa
密钥,而 github.com-x
使用新生成的 ~/.ssh/id_rsa_bitbucket
密钥。
- 示例:
git clone git@github.com-x:pineux/blog.git
其中 github.com-x是config中配置的别名,会映射到HostName github.com
5. 测试连接:
最后,你可以测试连接到你的代码托管服务提供商的远程仓库是否成功。例如:
ssh -T git@github.com
或者:
ssh -T git@github.com-x
如果一切设置正确,你应该能够成功连接到远程仓库而不需要输入密码。