Py学习  »  Git

【Git】windows添加多个git账号

遇见夏天 • 3 年前 • 251 次点击  
阅读 2

【Git】windows添加多个git账号

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

  1. ssh-keygen命令生成一组新的id_rsaid_rsa.pub
  2. 将目录切换到.ssh目录下
  3. 执行命令
  4. 需要给生成的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. 使用新的密钥

  1. 添加新的SSH keys到新账号的SSH设置中
  2. 可以使用命令行测试是否成功
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

  1. 执行ssh-agent让ssh识别新的私钥

  2. 启动ssh进程(了解ssh代理:ssh-agent),不能使用windows命令行

  3. 使用Git Bash启动进程

    1. 方法一,创建子shell,在子shell中运行ssh-agent进程,退出子shell自动结束代理。
    2. 方法二,单独启动一个代理进程,退出当前shell时最好使用ssh-agent -k关闭对应代理
    # 方法一
    ssh-agent $SHELL
    # 或
    ssh-agent bash
    
    # 方法二
    eval `ssh-agent`
    
    # 关闭当前进程
    ssh-agent -k
    复制代码

  4. 将私钥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"设置决定。

也可以在项目的.gitconfig文件中手动修改

[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"
复制代码

7. 参考资料

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/111513
 
251 次点击