1. 添加新的git账号
1. 取消git全局配置
如果之前已经全局配置过git账号,需要取消全局配置
# 查询已配置git账号
git config --global user.name
git config --global user.email
# 移除全局配置账号
git config --global --unset user.name
git config --global --unset user.email
2. 生成新的SSH KEYS
- 用
ssh-keygen
命令生成一组新的id_rsa
和id_rsa.pub
- 将目录切换到
.ssh
目录下 - 执行命令
- 需要给生成的
id_rsa
起一个名字id_rsa_github
ssh-keygen -t rsa -C "you@example.com"
3. 配置~/.ssh/config文件
配置多个账号的/.ssh/config
文件,没有的话手动添加,config文件没有后缀
# 该文件用于配置私钥对应的服务器
# first user
Host git@github.com
HostName https://github.com/
User git
IdentityFile ~\.ssh\id_rsa_github
# second user
Host git@xxx
HostName https:/xxx
User git
IdentityFile ~\.ssh\id_rsa
4. 使用新的密钥
- 添加新的SSH keys到新账号的SSH设置中
- 可以使用命令行测试是否成功
ssh -T git@github.com
结果:git@github.com: Permission denied (publickey).
拒绝连接
每次使用时需要将密钥添加到ssh进程中,默认密钥(id_rsa)不需要
ssh-add ~/.ssh/id_rsa_github
如果出现Could not open a connection to your authentication agent
的错误,就用以下命令:
ssh-agent bash
ssh-add ~/.ssh/id_rsa_github
ssh -T git@github.com
出现Hi XXX! You've successfully authenticated, but GitHub does not provide shell access.
2. 将新的私钥添加到ssh-agent
-
执行
ssh-agent
让ssh识别新的私钥 -
启动ssh进程(了解ssh代理:ssh-agent),不能使用windows命令行
-
使用
Git Bash
启动进程- 方法一,创建子shell,在子shell中运行
ssh-agent
进程,退出子shell自动结束代理。 - 方法二,单独启动一个代理进程,退出当前shell时最好使用
ssh-agent -k
关闭对应代理
# 方法一 ssh-agent $SHELL # 或 ssh-agent bash # 方法二 eval `ssh-agent` # 关闭当前进程 ssh-agent -k
- 方法一,创建子shell,在子shell中运行
-
将私钥
id_rsa_github
添加到ssh代理中# ssh-add ~/.ssh/key_name ssh-add ~/.ssh/id_rsa_github
3. 每次必须添加ssh-add
1. 原因
ssh-add 这个命令不是用来永久性的记住你所使用的私钥的。、实际上,它的作用只是把你指定的私钥添加到 ssh-agent 所管理的一个 session 当中。而 ssh-agent 是一个用于存储私钥的临时性的 session 服务,也就是说当你重启之后,ssh-agent 服务也就重置了。
2. 解决方法
在 git 的安装目录下的bash.bashrc
文件,末尾添加
#ssh-add 改为你电脑的秘钥名称
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_gitLab
这样,每次打开都会自动执行
Agent pid 12820
Identity added: /c/Users/Thinkpad/.ssh/id_rsa_github (/c/Users/Thinkpad/.ssh/id_rsa_github)
Identity added: /c/Users/Thinkpad/.ssh/id_rsa_gitLab (/c/Users/Thinkpad/.ssh/id_rsa_gitLab)
4. ssh-keygen的-C后面的邮箱有什么用?
邮箱仅仅是识别用的key,当你创建ssh的时候
-t = The type of the key to generate 密钥的类型
-C = comment to identify the key 用于识别这个密钥的注释
所以这个注释你可以输入任何内容,很多网站和软件用这个注释作为密钥的名字
5. git commit 名称
git commit
时显示的提交者记录和生成密钥时的邮箱名无关。由git config user.name "Your Name"
设置决定。
也可以在项目的.git
的config
文件中手动修改
[user]
name = Your Name
email = you@example.com
6. GitHub
当配置的user.email
同某个github账号的注册邮箱相同时,commit默认展示github账号名,此时.git/config
中设置的user.name 不起作用
git config user.name "Your Name"
git config user.email "you@example.com"