背景
我们在工作中会配置 ssh 账号,但是平时也会使用 github 管理自己的项目,于是我们可以为 github 平台创建一个新的 ssh 密钥。下面总结了创建多个 ssh 密钥的步骤(分别是公司的和自己 github 的)。
步骤(以MAC为例)
在文件夹
~/.ssh/
下创建两个文件夹,分别为company/
和github/
,前者存放公司的 ssh密钥,后者存自己github 的 ssh 密钥。下面的步骤以创建 github 密钥为例:在终端执行命令:
ssh-keygen -t rsa -C "[email protected]"
然后会提示
Enter file in which to save the key
,输入文件路径~/.ssh/github/id_rsa_github
,最后就会在该路径下生成id_rsa_github
和id_rsa_github.pub
两个文件(若直接回车的话,会保存在~/.ssh/
文件夹中)。然后出现
Enter passphrase (empty for no passphrase)
,直接回车即可。最后会出现创建成功的提示:
Your identification has been saved in .ssh_github/id_rsa_github. Your public key has been saved in .ssh_github/id_rsa_github.pub.
文件
id_rsa_github.pub
中保存的就是 ssh 公钥。可以利用命令pbcopy
将其复制到剪贴板,比如我的命令就是pbcopy < ~/.ssh/github/id_rsa_github.pub
。当然你也可以找到该文件手动复制。在 github 网站中添加该 ssh 公钥。
创建公司 ssh 密钥 的过程类似,不再赘述。
两个 ssh 密钥创建完毕后,在
~/.ssh/
文件夹中创建文件config
,添加如下内容:# The git info for company Host git.XXX.com # git别名,写公司的git名字即可 HostName git.XXX.com # git名字,同样写公司的git名字 User git # 写 git 即可 IdentityFile ~/.ssh/company/id_rsa #私钥路径,若写错会连接失败 # The git info for github Host github.com # git别名,写github的git名字即可 HostName github.com # git名字,同样写github的git名字 User git # 写 git 即可 IdentityFile ~/.ssh/github/id_rsa_github #私钥路径,若写错会连接失败
注:配置文件中各参数含义请参见扩展部分
网上很多文章说要执行命令
ssh-add
将 IdentityFile 添加到 ssh-agent中,具体到本文中就是执行ssh-add ~/.ssh/company/id_rsa
和ssh-add ~/.ssh/github/id_rsa_github
。其实这个操作只是把专用密钥添加到 ssh-agent 的高速缓存中,因此略过该步骤也不会有影响。这一步用于验证是否配置成功,以 github 为例,输入
ssh -T [email protected]
,若出现Hi xiaoxi666! You've successfully authenticated, but GitHub does not provide shell access.
这样的字段,即说明配置成功。公司的同理。
总结
本文描述了单机配置两个 git 平台ssh密钥的方法,多个账号同理。推荐在 ~/.ssh/
文件夹下为不同的平台建立不同的文件夹,方便管理。根据上述配置,我的 ~/.ssh/
文件夹下是这样子的:
├── company
│ ├── id_rsa
│ └── id_rsa.pub
├── config
├── github
│ ├── id_rsa_github
│ └── id_rsa_github.pub
扩展
关于配置文件 config
上面我们在
~/.ssh/
文件夹下创建配置文件,其实也可以指定位置,具体可查阅 ssh帮助手册(man 1 ssh
)。-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
Host 别名可以随意指定,比如你把 github 的 Host 别名设置为 banana,那你在测试的时候也可以输入
ssh -T banana
,以后 clone 项目时也可以用 banana 代替 github.com 。git 中的 user.name 和 配置文件中的 User 不是一个概念。前者是用来追踪代码的,提交代码时显示的名字就是它,比如在 github 中,我的 user.name 就是 xiaoxi666;而后者是登录提供 git 服务的平台(如这里的 github)的服务器主机时指定的用户名,比如 github 中 clone 项目时选择 ssh,链接均以
[email protected]
开头,@ 前面的 git 就是 github 对应服务器主机中的一个用户名,即上面设置的 User,@ 后面的 github.com 就是 HostName)。配置文件可指定的参数还有很多,如端口等,这里我们直接使用默认端口 22,因此没有再去指定。
其他
pbcopy
和pbpaste
是两个非常好用的命令,可查阅相关资料了解。- http://man.linuxde.net/ssh-add 这里描述了 linux 的 ssh-add 命令,可以了解下。