centos7下docker gitlab(三)同一客户端windows下使用多个git账号

429 阅读2分钟

场景

对于公司项目,一般是通过gitlab自建私有化项目。避免自己的电脑每次push要输入账号密码,clone需要通过Clone with SSH方式。
一般有以下两种场景:
1、多个账户在同一台电脑上,对同一个项目进行操作。
2、多个账户在同一台电脑上,对不同项目进行操作。

账号密钥

1、生成密钥

gitlab支持的SSH key pair有两种ED25519、RSA,以RSA为例,打开git bash

ssh-keygen -o -t rsa -b 4096 -C "email@example.com"

一路敲回车,其中email@example.com为你的gitlab账号邮箱。如果是windows默认生成的路径在/c/Users/qissen/.ssh/,可以看到生成了两个文件

id_rsa 私钥
id_rsa.pub 公钥

将两个文件名分别改成

id_rsa_email@example.com
id_rsa_email@example.com.pub

按照以上方法,可以生成多个账户的密钥,这些密钥为每个gitlab账号的访问gitlab时的密钥。打开gitlab gitlab.demo.com,在每个账号User Settings > SSH Keys 栏目下
将pub公钥添加进去,记得是公钥,如下

2、新增配置文件

在/c/Users/qissen/.ssh/下新建一个文件名config,无后缀,编辑内容

# email1@example.com
Host gitlab.demo.com
Port 8222
HostName gitlab.demo.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_email1@example.com


# email2@example.com
Host gitlab.demo.com
Port 8222
HostName gitlab.demo.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_email2@example.com


# email3@example.com
Host gitlab.demo.com
Port 8222
HostName gitlab.demo.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_email3@example.com
  • Host 别名,就是ssh -T git@gitlab.demo.com -p 8222ssh -T git@gitlab.demo.com -p 8222中的@后边的gitlab.demo.com。自己定义的,也可以是gitlab,比如ssh clone的那个ssh地址,这个没什么,只要HostName正确就可以。
  • HostName 域名或 ip,这里ip也可以
  • Port 端口号(默认22,可以不填,如果服务器修改了 ssh 登录端口号,此处需要修改)
  • User 登陆服务器用的账号
  • IdentityFile 密钥文件的位置

3、验证

ssh -T git@gitlab.demo.com -p 8222

结果成功

Welcome to GitLab, @xuyan!

如果出现错误,执行ssh -vvvT git@gitlab.demo.com -p 8222 查看问题所在。
成功后,我们发现在/c/Users/qissen/.ssh/下生成一个known_hosts。

clone

clone的项目将地址为

ssh://git@gitlab.demo.com:8222/workerman/thinkphp.git

默认的情况下,某些IDE可能会以其中一个账号进行clone,clone后,我们还需要通过git bash修改项目的身份。

git config user.name "email1@example.com"
git config user.email "email1@example.com"

如果这个账号默认账号作为ssh验证没有权限,就会找不到这个项目。我们可以先通过http clone项目人,然后在执行以上命令,设置成自己的账号。

push

可以push了。