git配置多个账号
场景:最近入职新公司,准备用自己的电脑来办公,主要有两个原因: 1、公司不给配mac 2、如果用自己的电脑,公司每个月给电脑补贴(蚊子再小也是肉)
但在公司代码仓库都在gitlab上,我自己平时也需要维护自己的github\gitee,这就需要在本地配置多个ssh key账户。
1、首先生成不同ssh
生成一对公司账户密钥,id_rsa_gitlab为文件名,如果你自己也有gitlab,可以修改名称与公司的做区分(比如加上公司简称)
$ ssh-keygen -t rsa -C "gitlab绑定的公司邮箱@xxx.com" -f ~/.ssh/id_rsa_gitlab
生成一对github账户密钥
$ ssh-keygen -t rsa -C "github绑定的邮箱@xxx.com" -f ~/.ssh/id_rsa_github
一路回车,成功后会有提示
ssh-keygen -t rsa -C "你的邮箱@qq.com" -f ~/.ssh/id_rsa_github
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/zhubei/.ssh/id_rsa_github
Your public key has been saved in /Users/zhubei/.ssh/id_rsa_github.pub
The key fingerprint is:
SHA256:covWm5H4iiDTbJ6i/U69RfofTgc3yxS5yUznwgUk/8k z993028171@qq.com
The key's randomart image is:
+---[RSA 3072]----+
| ..o |
| o o |
| = o |
| = X . |
| . S . @ E |
| o . O o = + |
|o = . * * o + |
|.* + o = * o |
|o.+o+ o.=.o |
+----[SHA256]-----+
这时候去.ssh文件夹看看生成的密钥
cd ~/.ssh/
或者直接打开文件夹
open ~/.ssh/
如下图展示:
.pub后缀的为公钥,没有后缀的为私钥,公钥配置后面需要配置到仓库的 ssh keys,私钥保存好别泄露
2、配置config
在.ssh目录新建一个文件config,配置仓库与密钥对应
# gitlab
Host gitlab.公司标识.com
HostName gitlab.公司标识.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_gitlab
User 公司邮箱@qq.com
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github
User git邮箱@qq.com
# 配置文件参数
# Host 识别的表示,对识别的模式,进行配置对应的的主机名和ssh文件
# HostName 要登录主机的主机名,如:github.com、gitlab.com,
# User 登录名
# PreferredAuthentications 优先验证方式 publickey,password,keyboard-interactive
# IdentityFile 与config里面的文件夹对应上,比如:github与id_rsa_github的密钥是对应的
3、配置仓库ssh key
以github为例
- 复制id_rsa_github.pub 的公钥
- 打开github.com/settings/ke…
- 点击
New SSH key把公钥粘贴进去,title可以不填 保存后如下图:
4、测试是否连接成功
$ ssh -T git@github.com //github的检测
$ ssh -T git@gitlab.com //gitlab的检测
// 成功后提示
// Hi xxx! You've successfully authenticated, but GitHub does not provide shell access.
git clone git@github.com:用户名/仓库名.git // git@git仓库地址:用户名/项目名.git
如果能正常拉取成功则没有问题
https拉取代码怎么避免每次都输入用户名密码
配置ssh key主要是为了pull、push代码不用每次输入密码,https怎么避免每次输入密码呢。
1、保存密码
下面命令会将下次弹框的账号和密码保存起来,永久使用。
git config --global credential.helper store
如果想要清除该账号和密码,使用如下命令:
git config --global credential.helper reset
想要临时存储使用如下命令,mac下
git config --global credential.helper "cache --timeout=3600" // 时间可以按需设置默认15min
windows下
git config --global credential.helper wincred
2、把密码存储在git地址里
git remote add origin http://yourname:password@github.com/name/project.git
这里有一点需要注意,如果用户名密码里面有@符号,需要转译%40
总结:
上面所有操作无非就是把本地生成的私钥与git仓库的公钥进行匹配,config文件主要提供的就是多账户解析,如果中间有失败的步骤,检查仓库、rsa文件名一致。