Git管理多个ssh密钥, 多账号配置

135 阅读1分钟

1.配置全局邮箱和用户名

通常为所在公司要求的邮箱和用户名

git config --global user.email "xxxxxxx@xxx.com"
git config --global user.name "username"

2.配置局部邮箱和用户名

通常为个人项目所用的邮箱和用户名,需先切换到仓库文件夹

git config --local user.email "xxxxxxx@xxx.com"
git config --local user.name "username"

3.生成SSH密钥

ssh-keygen -t rsa -C "xxxxxxx@xxx.com"

4.配置密钥地址和名称

密钥命名重复会造成覆盖

/c/Users/username/.ssh/id_rsa
/c/Users/username/.ssh/gitee_id_rsa
/c/Users/username/.ssh/github_id_rsa
/c/Users/username/.ssh/gitlib_id_rsa

5.添加新 ssh key

默认SSH只会读取id_rsa,所以为了让SSH识别新的私钥,需要将其添加到ssh agent如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent; 可执行ssh-agent bash命令后再执行ssh-add命令

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/github_id_rsa
ssh-add ~/.ssh/gitee_id_rsa
ssh-add ~/.ssh/gitlib_id_rsa

6.配置 config 文件

  • 跳转至.ssh文件夹
cd ~/.ssh
touch config
  • 以记事本方式打开config文件, 并输入以下内容

HostName是服务器的地址User是用户名,PreferredAuthentications照抄即可,IdentityFile是绝对路径

Host github.com
    HostName github.com
    User xxxxxxx@xxx.com
    PreferredAuthentications publickey
    IdentityFile /c/Users/username/.ssh/github_id_rsa
Host gitee.com
    HostName gitee.com
    User xxxxxxx@xxx.com
    PreferredAuthentications publickey
    IdentityFile /c/Users/username/.ssh/gitee_id_rsa
Host gitlib.com
    HostName gitlib.com
    User xxxxxxx@xxx.com
    PreferredAuthentications publickey
    IdentityFile /c/Users/username/.ssh/gitlib_id_rsa

7.测试SSH-KEY配置是否成功

此时需要输入刚才生成SSH-KEY时输入的私钥密码,输入后自行观察信息判断是否连接成功。

  • Github:
ssh -T git@github.com
  • Gitee:
ssh -T git@gitee.com
  • Gitlib:
ssh -T git@gitlib.com