同一台电脑的多ssh 配置

转载自:https://w3ctrain.com/2016/03/06/mutiple-ssh-key/

ps:此文基于你已经能够正常的生成sshkey

对于sshkey的功能这里就不多做介绍了,本文介绍的是一个更高级的功能:同一台电脑配置多个sshkey,方便本机在和不同的服务器(不同的项目之间)通信的时候自动切换账号

配置多个公钥

# 以下两种任选一种即可  
# 1. 生成新的ssh key并命名为`custom_rsa`  
ssh-keygen -t rsa -C "your_email@email.com" -f ~/.ssh/custom_rsa  

# 2. 或 打以下命令后,在询问时输入名称
ssh-keygen -t rsa -C "your_email@email.com"

修改 ~/.ssh 下的 config 文件

# desc: github (github@email.com)
Host github.com
    Hostname github.com
    User git
    PreferredAuthentications publickey
    Identityfile ~/.ssh/github

# desc: my_server_user (your_email@email.com)
Host your_domain_name_or_ip
    HostName your_domain_name_or_ip
    User git
    IdentityFile ~/.ssh/custom_rsa


# 以上各字段说明:
# Host:主机名字,不能重名
# HostName:主机所在域名或IP
# User:服务器上的用户名
# PreferredAuthentications:不填此行的话,如果pubkey验证不通过可以用密码方式;填了`publickey`只能通过公钥验证的方式
# IdentityFile:私钥路径


情景

我们有两个 github 账号,A 和 B 我们如何让两个 ssh 不互相影响,并且 git 操作时能智能匹配私钥?

解决方案:
上面的 Host 字段其实是任意的,git 操作时会有一个映射,将 Host 映射到目标域名或 ip (HostName)

所以我们可以这么干:

Host a.github.com
Hostname github.com
User git
Identityfile ~/.ssh/a_github_rsa

Host b.github.com
HostName github.com
User git  // 用户名称
IdentityFile ~/.ssh/b_github_rsa

注意:公私钥命名要对应

然后 ssh 的地址要更改一下,比如 A 账号的 repo 仓库原本的地址是

git@github.com:A/repo.git,配置了ssh 后,我们使用

git@a.github.com:A/repo.git

到这里就基本完成了(记得把公钥复制到远端仓库),使用ssh -T a.github.com测试一下吧

原文地址:https://www.cnblogs.com/yiludugufei/p/6298087.html