git之多SSH-key配置


1. 生成SSH-Key

  • Windows系统请使用Git bash操作
    # 生成第一个SSH-Key
    $ ssh-keygen -t rsa -C "你的邮箱” -f ~/.ssh/id_rsa_one
    # 生成第二个SSH-Key
    $ ssh-keygen -t rsa -C ""你的邮箱”” -f ~/.ssh/id_rsa_two
  • 创建完成之后 我们在.ssh的根目录下可以看到文件
    • C:\Users\Administrator.ssh 或者 C:\Users\电脑用户名.ssh

2. 添加私钥

# 在终端中执行

$ ssh-add ~/.ssh/id_rsa_gitlab
$ ssh-add ~/.ssh/id_rsa_github

# 如果执行ssh-add时提示 Could not open a connection to your authentication agent

# 可以先执行命令:
$ ssh-agent bash

# 然后再重新运行ssh-add命令即可
# 添加成功会出现提示:
# Identity added 等字样

3. 查看私钥列表是否存在

$ ssh-add -l

# 当我们可以看到2条私钥的时候就证明安装成功了

4. 修改配置文件config

  • 若.ssh目录(就是私钥所在的文件夹)下无config文件,那就需要自己创建config文件(可用vs code创建)
  • 创建后添加一下内容:
    # gitlab
    Host gitlab.com
    HostName gitlab.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_gitlab
    # github
    Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_github

5. 在gitlab、github网站中设置SSH keys

  • 在gitlab、github网站中找到用户设置,找到SSH keys
  • 在.ssh的根目录中找到对应网站的.pub结尾的文件,用记事本打开,然后复制内容到对应网站保存即可

6. 用ssh命令测试验证

$ ssh -T git@gitlab.com
$ ssh -T git@github.com

# 如果出现 Are you sure you want to continue connecting? 
# 直接输入 yes
# 然后重复上面的命令
# 验证通过会有类似“Welconme”或者“Hi”的欢迎字样


# 如果出现 ssh: connect to host github.com port 22: Connection timed out
# 请确认第四步是否完成:修改配置文件config
# 完成后重新执行:用ssh命令测试验证
# 出现:Are you sure you want to continue connecting (yes/no/[fingerprint])?
# 只输入yes,在重新'用ssh命令测试验'证即可

7. 清空私钥列表

$ ssh-add -D

文章作者: Damao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Damao !
  目录