git配置多端多账号
大约 3 分钟
前言
通过 git –version 命令,确认是否安装Git,显示当前安装的版本,则说明已安装。 为同一个设备,配置多个 git 账号,主要流程如下:
- 清空全局 user.name 和 user.email
- 为当前项目配置git用户名和邮箱
- 为不同的 git 账户生成不同的 ssh-key
- 将以上的 ssh-key 分别添加到 ssh-agent 信任列表
- 添加以上的公钥到自己的 git 账户中
- 在 config 文件配置多个 ssh-key
- 测试ceshiceeccee
1. 清空默认的全局 user.name 和 user.email
git config --global --unset user.name
git config --global --unset user.email查看git配置: git config --global --list
2、配置多个git的用户名和邮箱
a、单个配置
git config --global user.name "yourusername"
git config --global user.email "[email protected]"b、多个配置
注意: 这里git config命令没有带—global,表示这是一个局部的设置,也就是这个用户是当前项目的,而不是全局的。
git config user.name "yourusername"
git config user.email "[email protected]"c、删除配置
git config --unset user.name
git config --unset user.email3、生成多个密钥
生成SSH秘钥对
指定文件路径,方便后面操作:~/.ssh/id_rsa_gitee,id_rsa_github是秘钥的别名。
ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitee -b 4096 -C "[email protected]"
ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -b 4096 -C "[email protected]"4、将 ssh-key 分别添加到 ssh-agent 信任列表
ssh-agent -s
ssh-add ~/.ssh/id_rsa_gitee
ssh-add ~/.ssh/id_rsa_github如果看到 Identitiy added: ~/.ssh/id_ras_github,就表示添加成功了。
5、添加公钥到自己的 git 账户中
打开文件复制,带 pub 的文件即copy公钥,如id_rsa_gitee.pub、id_rsa_github.pub,复制到到 git 账户中粘贴即可
6、在 config 文件配置多个 ssh-key
在生成密钥的.ssh 目录下,新建一个config文件,然后配置不同的仓库 (这是配置不同平台账号,同一平台多账号,直接看进阶配置)
#gitHub的配置
Host github.com
HostName github.com
User github
IdentityFile ~/.ssh/id_rsa_github
# gitee的配置
host gitee.com # 别名,最好别改
Hostname gitee.com #要连接的服务器
User gitee #用户名
#密钥文件的地址,注意是私钥
IdentityFile ~/.ssh/id_rsa_gitee7、测试
ssh -T [email protected]
ssh -T [email protected]8、进阶配置
当同一平台多账号时,编辑~/.ssh/config文件,host需配置不同的别名,且添加远程仓库时,也需要使用别名,否则会找不到对应的密钥,报权限问题。
- 配置config文件
# 配置第一个GitHub账号
Host github-first
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_first
# 配置第二个GitHub账号
Host github-second
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_second- 项目文件中添加对应别名的远程仓库
# 使用第一个GitHub账号克隆仓库
git clone git@github-first:username/repo.git
# 使用第二个GitHub账号克隆仓库
git clone git@github-second:username/repo.git- 测试
ssh -T git@github-first
ssh -T git@github-secondtips:
- 测试通过了,但是提交代码,但是提交的时候还是要求输入用户名和密码。
把remote的地址https开头的换成git开头