[关闭]
@Rookie 2020-08-20T03:01:55.000000Z 字数 1903 阅读 966

配置多个 SSH Key

Tools


起因
前几天同事问我, 一个Mac 下怎么配置多个 SSH key , 使用场景是 SSH key 可以连接 github 和 公司自己的 gitlab. 之前也碰到过这样的问题, 同事说要配置 config 文件 , 我说不用啊 , 经过研究发现实力打脸, 在不配置 config情况下, 只有id_rsa.pub 类型的 SSH Key 是好用的 , 其余的重新起名字的都没有办法生效. 实力打脸 ,发现自己都是通过 http来 clone 的, 拍拍拍


SSH Key 是什么
SSH 密钥对可以让您方便的登录到 SSH 服务器,而无需输入密码。由于您无需发送您的密码到网络中,SSH 密钥对被认为是更加安全的方式。再加上使用密码短语 (passphrase) 的使用,安全性会更上一层楼。 同时,我们可以使用 SSH agent 来帮助我们记住密码短语,无需我们记住每一个密钥对的密码短语,减轻了我们的负担。


多个SSH Key
生成1个SSH Key:

$ ssh-keygen -t rsa -C "youremail@xxx.com"

按回车后:

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/Shinancao/.ssh/id_rsa): id_rsa_TestSSH_github(取个名字)
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in
id_rsa_TestSSH_github.
Your public key has been saved in
id_rsa_TestSSH_github.pub.

最好每次生成时都给SSH Key取个名字,这样后面在管理时自己也一目了然。我这里的格式是idrsa项目名git提供方,我生成的所有key都遵循这个规则命名。建议你也有你自己的一种命名方式,并且保持统一。如果不取名字,默认的是idrsa,如果后面生成时不命名,会把这个覆盖掉。密码可以不设置,免得每次提交时还要输入一次,安全性自己衡量吧。第一次生成key时,会在~目录下创建一个.ssh目录。

cd ~/.ssh
$ ls

把idrsaTestSSH_github.pub添加到github对应的项目的Deploy keys中。
创建本地的配置文件 ~/.ssh/config,编辑如下:

Host TestSSH.github.com
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_TestSSH_github
Host YourProjectName.gitlab.com
HostName gitlab.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_YourProjectName_gitlab

Host的名字可以随意取,我这边按照的规则是项目名.git服务器来源,接下来会用到这个名字。测试是否配置正确:

ssh -T git@TestSSH.github.com (就是刚刚你给Host取的名字)

敲一下回车,如下出现下面的提示就连接成功了:

Hi shinancao/TestSSH! You've successfully authenticated, but GitHub does not provide shell access.

基本上就大功告成了 . 后面还有一些别的设置, 可以查看参考连接
最后放出我自己的 config 文件

#github-- myself

Host github.com
HostName github.com
User 411152955@qq.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/myself

#github -- ued

Host github.com
HostName github.com
User ued@tton.co
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_ued

#tton gitlab

Host git.tton.co
HostName git.tton.co
User liuyafang@tton.co
IdentityFile ~/.ssh/git_tton_rsa

忠告
好好学习, 不被打脸.....

参考链接

同一个Mac,配置多个SSH Key
SSH keys

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注