一个客户端设置多个 github 账号

  1. 前期工作
  2. SSH 生成
  3. SSH 配置 config 文件
  4. 测试
  5. 在 Git 项目中配置账号关联
  6. 项目路径设置

前期工作

两个 GitHub 账号(假设两个账号为 one,two)
取消 Git 全局设置

git config --global --unset user.name
git config --global --unset user.email

SSH 生成

生成 id_rsa 私钥,id_rsa.pub 公钥。one 可以直接回车,默认生成 id_rsaid_rsa.pub

cd ~/.ssh
ssh-keygen -t rsa -C "one@xxx.com"

添加 two 会出现提示输入文件名,输入与默认配置不一样的文件名,如:id_rsa_two

cd ~/.ssh
ssh-keygen -t rsa -C "two@xxx.com"  #  之后会提示输入文件名

GitHub 添加公钥 id_rsa.pub 、 id_rsa_two.pub
分别登陆 one,two 的账号,在 Account Settings 的 SSH Keys 里,点 Add SSH Keys ,将公钥 (.pub 文件) 中的内容粘贴到 Key 中,并输入 Title。
添加 ssh Key

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_two

可以在添加前使用下面命令删除所有的 key

ssh-add -D

最后可以通过下面命令,查看 key 的设置

ssh-add -l

SSH 配置 config 文件

我们需要在目录: ~/.ssh/ (linux)C:\Users\admin\.ssh\ (windows)

创建config文件

touch config

linux 下 config 配置:

# default one
Host github.com
    HostName github.com
    User git
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa
    
# two
Host two.github.com
    HostName github.com
    User git
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_two

windows 下 config 配置:

# default one
Host github.com
    Hostname github.com
    User git
    PreferredAuthentications publickey
    IdentityFile C:\\Users\\\admin\\.ssh\\id_rsa
# two
Host two.github.com
    Hostname github.com
    User git
    PreferredAuthentications publickey
    IdentityFile C:\\Users\\\admin\\.ssh\\id_rsa_two
  • 这里必须采用这样的方式设置,否则 push 时会出现以下错误:

ERROR: Permission to two/two.github.com.git denied to one.

Host : 相当于一个别名,远程仓库地址的域名别名它涵盖了下面一个段的配置,我们可以通过他来替代将要连接的服务器地址。这里可以使用任意字段或通配符。访问ssh的时候如果服务器地址能匹配上这里Host指定的值,则Host下面指定的HostName将被作为最终的服务器地址使用,并且将使用该Host字段下面配置的所有自定义配置来覆盖默认的/etc/ssh/ssh_config配置信息。
HostName :真正连接的服务器地址
User:自定义的用户名
PreferredAuthentications 指定优先使用哪种方式验证,支持密码和秘钥验证方式
IdentityFile:指定本次连接使用的密钥文件

测试

ssh -T git@github.com        #  测试 one ssh 连接
# Hi ***! You've successfully authenticated, but GitHub does not provide shell access.

ssh -T git@two.github.com    #  测试 two ssh 连接
# Hi ***! You've successfully authenticated, but GitHub does not provide shell access.

在 Git 项目中配置账号关联

可以用 git init 或者 git clone 创建本地项目
分别在 one 和 two 的 git 项目目录下,使用下面的命令设置名字和邮箱

git config user.name "__name__"            #  __name__ 例如 one
git config user.email "__email__"          #  __email__ 例如 one@126.com

查看 git 项目的配置

git config --list

项目路径设置

# one项目 使用 github.com
git clone git@github.com:用户名/项目名.git
# two项目 使用 two.github.com
git clone git@two.github.com:用户名/项目名.git

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 lzdong@foxmail.com

×

喜欢就点赞,疼爱就打赏