如何配置多个 git 仓库 ssh

677 阅读2分钟

试想一下一个场景,当你35岁毕业,选择一份站着把钱赚的岗位(外包),甲方爸爸多,这个时候是否需要链接多个仓库呢?多个仓库是否需要配置多个 ssh 呢。接下来我们将一步步操作配置多个 ssh

一、生成密钥 key

cd ~/.ssh
ssh-keygen -t rsa -C "your_email@youremail.com"  // 仓库账号关联邮箱

默认密钥要是 id_rsa 和 id_rsa.pub,既然是多个 ssh ,那么肯定是需要多对密钥

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxxx/.ssh/id_rsa): xxx_rsa  //输入自定义密钥文件名称 

Enter passphrase (empty for no passphrase):
Host gitlab
Enter same passphrase again:

这里两次空格就行,不设置密码在接下 ssh 连接时就需要输入密码。

到这里就生成了相应的一对密钥:xxx_rsa(私钥)   xxx_rsa.pub(公钥)

二、ssh-key 添加到 ssh-agent

ssh-add -l  // 查看 ssh-agent


The agent has no identies

默认的 id_rsa 会自动关联不需要手动添加,此时需要手动添加多个 ssh-key;-K 表明添加到钥匙串中

ssh-add -K ~/.ssh/xxx_rsa   

三、配置 ssh config文件

~/.ssh 路径下

touch config
vim config

# 字段说明
# Host:Host可以看作是一个你要识别的模式,对识别的模式,进行配置对应的的主机名和ssh文件
# HostName:要登录主机的主机名
# PreferredAuthentications:publickey  表明远端公钥匹配本机私钥
# User:git仓库登录名 不是必须项
# IdentityFile:指明本机私钥路径
# port 默认 22 可不写Host git
HostName git.xxx.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/xxx_rsa
User xxx
Port 22

四、添加公钥到 git 上

这里就不在说了

五、验证是否成功

ssh -T git@xxx.com

注意:

如果出现

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
SHA256:*****************.
Please contact your system administrator.
Add correct host key in /c/Users/用户名/.ssh/known_hosts to get rid of this message.
Offending DSA key in /c/Users/用户名/.ssh/known_hosts:6
Host key for git.code1.com has changed and you have requested strict checking.
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

原因是 known_hosts 不匹配,删除即可,再次连接

rm -rf ~/.ssh/known_hosts

什么是 known_hosts

A通过ssh首次连接到B,B会将公钥1(host key)传递给A,A将公钥1存入known_hosts文件中,以后A再连接B时,B依然会传递给A一个公钥2,OpenSSH 会核对公钥,通过对比公钥1与公钥2 是否相同来进行简单的验证,如果公钥不同,OpenSSH会发出警告, 避免你受到DNS Hijack之类的攻击。