Git多密钥配置

参考的博客

生成密钥

打开git bash

ssh-keygen -t rsa -C "你的邮箱" -f ~/.ssh/id_rsa_gitee
ssh-keygen -t rsa -C "你的邮箱" -f ~/.ssh/id_rsa_github

添加密钥到ssh-agent中

Git默认读取的文件文件名为id_rsa,因此我们需要将生成的密钥添加到ssh-agent中。

# 添加密钥地址到ssh-agent
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_gitee
# 如果出错,可以使用这条命令,再执行上方代码
ssh-agent bash

编写配置文件

编写config文件(~/.ssh目录下),若没有则自行新建。

# github
Host github.com
HostName github.com
PreferredAuthentications publickey  
IdentityFile ~/.ssh/id_rsa_github  
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey  
IdentityFile ~/.ssh/id_rsa_gitee
# 相关参数
# Host:对识别的模式,进行配置对应的主机名和ssh文件
# HostName : 登录主机的主机名
# PreferredAuthentications :设置登录方式(publickey为使用密钥登录,password为使用密码登录)
# IdentityFile :私钥全路径名

查看密钥并在git/gitee添加公钥

查看生成的公钥

cat ~/.ssh/id_rsa_gitee.pub

复制公钥到git/gitee即可

github同理

最后测试下是否添加成功

ssh -T git@github.com
ssh -T gitee@github.com

常见问题

git配置ssh登陆后,push却一直提示要输入密码?

参考文档

这是因为我们在clone的时候采用的是https协议。https协议会每次要求你输入账户密码,而git协议才可以使用ssh-keys文件,实现git push自由。

查看remote协议

git config --get remote.origin.url

更改为ssh协议 同理也改为https协议

git remote set-url origin git@github.com:shouyaya/spring_study.git
posted @ 2021-09-30 11:42  shouyaya  阅读(668)  评论(0编辑  收藏  举报