Git配置多账号SSH登录不同的服务器

一般来说在公司做项目,都是用公司分配的邮箱。例如通过在Git bash里面运行git config --global命令配置全局的Git账号:

$ git config --global user.name "<name>"
$ git config --global user.email "<email>"

有时候也有例外,比如我们可能有多个通过SSH访问的Git Repo,并且想在不同的Repo上使用不同的身份(不同的SSH key)。例如,公司基于.Net平台的项目使用的是Azure DevOps上远程Git仓库,需要使用公司的账号;私人的项目使用GitHub上的远程Git仓库,需要使用个人的账号。
这种情况可以通过下面的设置来实现:

第一步,为每个Git服务器生成独立的SSH key

在Git bash中使用ssh-keygen命令生成SSH key,常用参数如下:
-t指定密钥类型为rsa
-C 指定邮箱
-f指定文件存放的路径和名称。在Windows系统里,~/.ssh就是C:\Users<当前登录用户名>.ssh文件夹。
-P ''指定密码为空。这个密码是用于保护私钥的,如果填入密码,git在通信时会要求输入密码。
下面命令为azure devops生成SSH Key,将在~/.ssh文件夹生成id_rsa_azuredevops和带.pub扩展名的两个文件:

$ ssh-keygen -t rsa -C "efrey.kong@EKStudio.com" -f ~/.ssh/id_rsa_azuredevops -P ''

下面命令为GitHub生成SSH Key,命令完成后会在~/.ssh文件夹生成id_rsa_github和id_rsa_github.pub两个文件:

$ ssh-keygen -t rsa -C "efrey.kong@gmail.com" -f ~/.ssh/id_rsa_github -P ''

第二步,配置本地的SSH config

在~/.ssh文件夹中编辑config文件。如果没有此文件则用记事本新建一个,保存时需要注意不要.txt的扩展名。
在文件里配置如下内容:

#Company repo
Host ssh.dev.azure.com
HostName ssh.dev.azure.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_azuredevops

#Personal repo
Host github.com
HostName ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_github

当Git命令需要访问网络时,SSH会按照命令中指定的host(例如git clone git@host/repopath)在config中寻找匹配的host,找到后使用HostName作为实际的通信服务器名,使用IdentityFile指定的key作为密钥同服务器通信。

第三步,将公钥文件上传到Git服务器

SSH Public Key上传的过程略(参考官网的说明)。

上传完成后可以用ssh -T命令验证下(ssh -vT 可以输出debug信息):

$ ssh -vT git@github.com
OpenSSH_7.9p1, OpenSSL 1.1.1a  20 Nov 2018
debug1: Reading configuration data /c/Users/efrey/.ssh/config
debug1: /c/Users/efrey/.ssh/config line 16: Applying options for github.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to ssh.github.com [192.30.253.123] port 22.
debug1: Connection established.
debug1: identity file /c/Users/efrey/.ssh/id_rsa_github type 0
debug1: identity file /c/Users/efrey/.ssh/id_rsa_github-cert type -1
...
debug1: Authentications that can continue: publickey
...
Hi efreykongcn! You've successfully authenticated, but GitHub does not provide shell access.
...

从debug输出的信息中可以看到,通信使用的是id_rsa_github证书,以及已认证的欢迎信息。

如果此时本地库还没有创建,则从服务器克隆一个本地库:

$ git clone git@github.com:efreykongcn/PrimerRepo.git
Cloning into 'PrimerRepo'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.

第四步,设置项目Git仓库的工作账号

然后,在Git Repo的工作目录下设置local user.name和user.email。
在Git Repo工作目录位置打开Git bash进行设置:

$ git config --local user.name "<your name>"
$ git config --local user.email "<your email>"

这样,在项目里就会以这个账号向Git仓库提交代码了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。