目录

深度学习同一台电脑使用ssh配置多个github账号

深度学习——同一台电脑使用ssh配置多个github账号

如果一台电脑只有一个github账号,那么进行默认的ssh配置,通过git拉取和提交代码即可,但在实际的工作中,有时候需要在一台电脑登录多个github账号,将不同的项目代码提交到不同的github账号,这个时候如果仅仅只是使用ssh默认配置,私钥和公钥将无法完成 一对一 配对,为此我们需要进行ssh的``多对多```配置,简单来讲就是原本两个人用一双筷子,现在两个人用两双筷子。

当你看到这篇文章时,默认你已经有了一些git相关的基础知识,这篇文章里不进行赘述。

为了举例方便,这里使用 “one” 和 “two” 两个账户。

步骤一 :使用cd ~/.ssh切换工作目录,然后使用如下命令生成两个钥匙,中间一路回车。

ssh-keygen -t rsa -f ~/.ssh/id_rsa_one  -C "one@qq.com"     #-C 参数里面是注释,可以随便填
ssh-keygen -t rsa -f ~/.ssh/id_rsa_two  -C "two@qq.com"

这样会在~/.ssh目录下生成四个文件:

id_rsa.one      #账号 one 的私钥
id_rsa.one.pub  #账号 one 的公钥
id_rsa.two
id_rsa.two.pub

步骤二:创建配置文件 config

在 ~/.ssh目录下新建 config 文件,令不同 Host 实际映射到同一 HostName,但密钥文件不同。

touch config    #创建 config
vim config      #编辑 config

写入以下内容

Host  one.github.com      #one.github.com是自己取的名,可以随便取
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_one


Host two.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_two

步骤三:添加秘钥到ssh识别列表

ssh-add ~/.ssh/id_rsa_one
ssh-add ~/.ssh/id_rsa_two

步骤四:添加 SSH key 及 测试

分别登陆两个 github 账号,在 Settings —> SSH and GPG keys 中,点击 “new SSH key”,把 “id_rsa.one.pub” 和 “id_rsa.two.pub"这两个公钥的内容分别添加到相应的账号中。

步骤五:为了确认我们可以通过 SSH 连接 github,可通过输入下面命令来验证

ssh -T git@one.github.com
ssh -T git@two.github.com

如果看到下面信息,就说明连接正常。

Hi one! Youve successfully authenticated, but GitHub does not provide shell access.
Hi  two! Youve successfully authenticated, but GitHub does not provide shell access.

步骤六:用户名和邮箱配置

注意:因为一台电脑上配置了多个 github 账号,所以就不能再配置全局的用户名和邮箱了,而是在不同的仓库下,如果需要连接不同的 git 账号,配置相应的局部用户名和邮箱即可,如果之前配置过全局的用户名和邮箱,需要取消配置。

取消全局 用户名/邮箱 配置

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

设置局部 用户名/邮箱 配置

git config user.name xxxx
git config user.email xxxx@xx.com

步骤七:使用 git克隆仓库

原来写法

git clone git@github.com: 用户名/learngit.git

现在写法(将github.com 替换为之前设置的别名,这里替换为one.github.com)

git clone git@one.github.com: 用户名/learngit.git

步骤八:远程地址添加或者修改

添加

git remote add origin git@one.github.com:用户名/项目名.git    

修改

git remote set-url origin git@one.github.com:用户名/项目名.git

参考文献