同一台电脑管理多个ssh key

默认情况下,我们在本地电脑生成的密钥都是 id_rsa 和 id_rsa.pub ,git 默认情况下也只会读取这个私钥,所以我们需要修改一些配置来支持多个SSH Key。

本文基于Linux系统,Windows系统类似

第一步:生成ssh公私钥

ljh@pc:~/.ssh$ ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ljh/.ssh/id_rsa): id_rsa_gitlab


第二步:把生成的key添加到ssh-agent里面

ssh-agent是一个私钥的管理工具,当我们需要通过不同的私钥去连接不同的服务器时,需要我们手动输入私钥密码,ssh-agent可以免去这项工作,那么我们需要将新的key 添加到ssh-agent里面管理,可以通过ssh-add命令,首先我们看下里面有哪些key:

ljh@pc:~/.ssh$ ssh-add -l
2048 SHA256:xxx /home/ljh/.ssh/id_rsa (RSA)
默认情况下id_rsa已经存在里面,那么我们此时应该把上面新建的key也添加到里面:

ljh@pc:~$ ssh-add /home/ljh/.ssh/id_rsa_gitlab
Identity added: /home/ljh/.ssh/id_rsa_gitlab (/home/ljh/.ssh/id_rsa_gitlab)


第三步:配置config,关联本地与远程的key

在.ssh/ 目录里创建一个config文件,通过配置信息告诉git什么情况下使用新的key:

ljh@pc:~/.ssh$ touch config
ljh@pc:~/.ssh$ vim config
添加下面内容:

# github
Host github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
User ljh
 
# gitlab
Host gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_gitlab
User ljh
User填写的是gitlab账号。

第四步:测试

测试:

ssh -T [email protected]
如果提示如下 请输入 yes 后回车:

The authenticity of host 'gitlab.com (13.250.177.223)' can't be established.
ECDSA key fingerprint is SHA256:FQGC9Kn/eye1W8icdBgrQp+KkGYoFgbVr17bmjey0Wc.
Are you sure you want to continue connecting (yes/no)?
连接成功会返回:

You've successfully authenticated, but GitHub does not provide shell access.
文章知识点与官方知识档案匹配,可进一步学习相关知识
————————————————
版权声明:本文为CSDN博主「嗯嗯~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_41977631/article/details/106560574/

猜你喜欢

转载自blog.csdn.net/BersonKing/article/details/130336477