Git 配置多个SSH-Key

306 阅读2分钟

当公司存在多个代码托管平台时,需要配置多个SSH-Key来支持开发。
假设当前有两个GitLab:

  1. git.code1.com 对应注册账号的邮箱: example1.qq.com
  2. git.code2.com 对应注册账号的邮箱: example2.qq.com

1. 生成多个SSH-Key

进入默认保存.ssh的目录中,注: windows中为C:\Users\用户名.ssh,mac中为~/.ssh, 此处以windows为例

# 生成第一个SSH-Key, 连续回车, 确认生成成功
ssh-keygen -t rsa -C "example1.qq.com" -f ./code1_id_rsa
# 查看当前生成的公钥内容, 复制输出的内容, 粘贴到 git.code1.com 中下图位置
cat code1_id_rsa.pub

image.png

点击Add Key, 保存公钥。

# 生成第二个SSH-Key
ssh-keygen -t rsa -C "example2.qq.com" -f ./code2_id_rsa
# 查看当前生成的公钥内容, 复制输出的内容, 粘贴到 git.code2.com 中下图位置
cat code2_id_rsa.pub

image.png

点击Add Key, 保存公钥。

2. 编辑Config配置文件

确认当前.ssh目录下是否存在config文件, 有则编辑, 无则添加, 此config文件用于区分多个SSH-Key。

# 字段说明
# Host : Host可以看作是一个你要识别的模式,对识别的模式,进行配置对应的的主机名和ssh文件
# HostName : 要登录主机的主机名
# User : 登录名
# IdentityFile : 指明上面User对应的identityFile路径

# code1
Host git.code1.com
    HostName git.code1.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/code1_id_rsa
    User code1平台的账号名

# code2
Host git.code2.com
    HostName git.code2.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/code2_id_rsa
    User code2平台的账号名

3.验证是否成功

ssh -T git@github.com
Hi *** You've successfully authenticated, but *** does not provide shell access.

4. 如果出现无法连接问题

Permission denied(Publickey)

此处以 Code1 平台连接不上为例:

# ssh-add命令是把专用密钥添加到ssh-agent的高速缓存中
ssh-agent bash
ssh-add code1_id_rsa

运行完成后, 再次尝试, 如果还是不生效, 则去编辑本地Git安装目录下的Git\etc\ssh下的ssh_config文件, 添加如下内容:

Host *
    IdentityFile ~/.ssh/code1_id_rsa  # 秘钥的位置, 此时以code1举例
    HostkeyAlgorithms +ssh-rsa  # 使 openssh 支持 rsa 算法
    PubkeyAcceptedAlgorithms +ssh-rsa
    PubkeyAcceptedKeyTypes +ssh-rsa

再次验证是否连接成功, 正常情况下, 走到这一步, 基本就完成了, 如果还是出现了以下问题:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:*****************.
Please contact your system administrator.
Add correct host key in /c/Users/用户名/.ssh/known_hosts to get rid of this message.
Offending DSA key in /c/Users/用户名/.ssh/known_hosts:6
Host key for git.code1.com has changed and you have requested strict checking.
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

参考解决方案:

# 删除.ssh目录下的known_hosts文件
rm -rf ~/.ssh/known_hosts

如果还是不行... 那就从头再来一次吧🤣

5. 参考资料

image.png