一台电脑配置多个Git账户
背景
在使用Git
作为仓库使用的时候,我们会有Github
账号公司也有Gitlab
账号,如果需要在同一台电脑下配置多个Git
账号的话,我们可以通过SSH Key
配置多个公钥。
SSH Key的配置
1.首先先清空全局的邮箱和用户名称
git config --global --unset user.name
git config --global --unset user.email
2.Windows
下打开 Git Bash
,创建 SSH Key
,按提示输入密码,可以不填密码一路回车
# 生成github的ssh-key,注册邮箱填github的注册邮箱,然后在用户主目录下/.ssh/下会生成id_rsa(私钥)、id_rsa.pub(公钥)
$ ssh-keygen -t rsa -C "注册邮箱" -f ~/.ssh/id_rsa
# 生成gitlab的ssh-key,注册邮箱填gitlab的注册邮箱,然后在用户主目录下/.ssh/下会生成id_rsa_work(私钥)、id_rsa_work.pub(公钥)
$ ssh-keygen -t rsa -C "注册邮箱" -f ~/.ssh/id_rsa_work
3.此时用户目录下/.ssh/
有4个文件,因为Git
默认使用id_rsa
,我们需要将密钥添加进去。
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa_work
$ ssh-add -l
#如果添加成功,这里会打印对应的配置信息
4.配置config
,让Git
根据不同的域名使用不同的私钥。
$ vim ~/.ssh/config
# 账号1-github
HOST github.com #github别名
hostname github.com #github地址
User githubUsername #github用户名
IdentityFile C:\Users\Administrator\.ssh\id_rsa #github私钥地址
PreferredAuthentications publickey #首选认证方式
# 账号2-公司的gitlan私服
HOST git.gitlab.com #gitlab私服别名
hostname git.gitlab.com #gitlab私服地址
User gitlabUsername #填写gitlab私服的用户名
IdentityFile C:\Users\Administrator\.ssh\id_rsa_work #gitlab私钥地址
PreferredAuthentications publickey #首选认证方式
5.Github
& Gitlab
新增 SSH Key
新增SSH Key
,Github
和Gitlab
的操作如出一辙,这里就长话短说以Github
为例了,登录 GitHub
,点击头像—>Setting
—>SSH and GPG keys
—>New SSH key
—>填写title
和Key
(title
:随意填,相当于给SSH Key
取一个别名,Key
就是将公钥填入)
6.测试Github
& Gitlab
的SSH Key
是否成功
$ ssh -T git@github.com
$ ssh -T git@git.gitlab.com
如果出现 You’ve successfully authenticated, but GitHub does not provide shell access
。这就表示已成功连上.
遇到的问题
1.测试Gitlab
的SSH Key
是否连接成功,出现Permission denied (publickey).
$ ssh -T git@git.gitlab.com
git@git.gitlab.com: Permission denied (publickey).
#使用ssh -v查看详细日志
$ ssh -vT git@git.gitlab.com
...
...
debug1: send_pubkey_test: no mutual signature algorithm
debug1: No more authentication methods to try.
git@git.gitlab.com: Permission denied (publickey).
关注的最后面三行日志,显示没有匹配的算法,查阅相关资料,openssh
8.2版本之后,默认关闭SSH-RSA
算法,该算法存在安全隐患(OpenSSH to deprecate SHA-1 logins due to security risk | ZDNet),当然我们可以重新启用它,但存在安全风险。在config
的Gitlab
配置中添加如下一行
PubkeyAcceptedKeyTypes +ssh-rsa
再次运行
$ ssh -T git@git.gitlab.com
出现 You’ve successfully authenticated, but GitHub does not provide shell access
,连接成功!
最后在对应的项目下设置对应的用户名以及邮箱名就可以快乐的提交代码了
git config user.email "useremail"
git config user.name "username"
完工!