Git源码库和SSH远程登录的多账号配置

Git源码库多账号配置,本质上还是SSH远程登录多账号配置的扩展。先看一下基础的SSH远程登录多账号配置。

在 ~/.ssh/ 下创建一个名为 config 的文件。里面写上如下配置:

Host testVM
    HostName xxx.xxx.xxx.xxx
    User username
    Port 22
    IdentityFile /path/to/my/private/key/testVM.pem

注意所有私钥文件权限要设置为 400,config 文件权限要设置为 600。

chmod 400 /path/to/my/private/key/testVM.pem
chmod 600 ~/.ssh/config

然后就可以用代号运行简化的 SSH 远程登录了,比如 ssh testVM。

在此基础之上,当我们有多个 Git源码库需要同时管理时,还是在 config 文件中增加 Git服务器的访问配置。比如:

# Github
Host github.com
    User github_user_name
    IdentityFile /path/to/my/private/key/github.pem

# Azure Repos,Azure上托管的私有源码库
Host ssh.dev.azure.com
    User git
    IdentityFile /path/to/my/private/key/repos.pem

需要注意的是配置Git服务器时,不要写 HostName 项,而是直接把Git服务器域名写在 Host 段,这样才能让ssh 和git客户端正常找到相关服务器的配置,加载到需要的私钥。

之后我们就可以用 ssh -Tv [email protected]来验证授权了。其中 -T 参数表示测试验证,-v 表示以1级详细程度输出调试信息。

返回结果比较长,只节选重要的部分:

OpenSSH_7.5p1, OpenSSL 1.0.2o  27 Mar 2018
debug1: Reading configuration data /home/mobaxterm/.ssh/config
debug1: /home/mobaxterm/.ssh/config line 12: Applying options for github.com
...
debug1: Connecting to github.com [192.30.255.113] port 22.
debug1: Connection established.
...
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /path/to/my/private/key/github.pem
debug1: Authentication succeeded (publickey).
Authenticated to github.com ([192.30.255.113]:22).
debug1: Requesting X11 forwarding with authentication spoofing.
debug1: Requesting authentication agent forwarding.
X11 forwarding request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi github_user_name! You've successfully authenticated, but GitHub does not provide shell access.

使用 Azure DevOps Repos 作源码库时,使用 ssh -Tv 来验证更为重要,因为它返回的验证成功信息是在调试中的,不加 -v 时会让人感觉验证失败了。

ssh -T [email protected]

X11 forwarding request failed on channel 0
shell request failed on channel 0

加上 -T 参数再看

ssh -Tv [email protected]

OpenSSH_7.5p1, OpenSSL 1.0.2o  27 Mar 2018
debug1: Reading configuration data /home/mobaxterm/.ssh/config
debug1: /home/mobaxterm/.ssh/config line 4: Applying options for ssh.dev.azure.com
...
debug1: Connecting to ssh.dev.azure.com [20.189.107.3] port 22.
debug1: Connection established.
...
debug1: Authenticating to ssh.dev.azure.com:22 as 'git'
debug1: Host 'ssh.dev.azure.com' is known and matches the RSA host key.
debug1: Found key in /home/mobaxterm/.ssh/known_hosts:3
debug1: Authentications that can continue: password,publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /path/to/my/private/key/repos.pem
debug1: Authentication succeeded (publickey).
Authenticated to ssh.dev.azure.com ([20.189.107.3]:22).
...
X11 forwarding request failed on channel 0
shell request failed on channel 0

就可以看到验证通过的信息了。

到此,Git 配置多账号就完成了。下面就可以 git clone 开始快乐编码了.