问题
之前一直对各种 git 服务需要的 ssh key 的认证都是懵懵懂懂的状态,直到我偶尔用了多个git服务,比如 github 、bitbucket ,出现了好几次无法提交和拉取的问题,我才意识到我多次修改了 id_rsa 文件,为不同的 git 服务创建 ssh key 的同时也覆盖了之前 git 服务器的 key 。心想肯定有办法让多个服务共存吧,于是 Google 了一番,方法并不难。
步骤
创建密钥
1.创建一个密钥
$ ssh-keygen -t rsa
2.输入保存ssh key 密钥的文件名称 id_rsa_github
。
Enter file in which to save the key (/root/.ssh/id_rsa):/root/.ssh/id_rsa_aaa
3.输入两次密码,要求最低不能低于8位。
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
重复上面的步骤可以创建多个密钥,比如你有多个git账户
id_rsa_github
id_rsa_bitbucket
id_rsa_oschina
添加到 ssh-agent
用 ssh-add
命令把创建的密钥添加到 ssh-agent 里
$ ssh-add ~/.ssh/id_rsa_github
更新提示:ssh-add
命令只能临时性添加到系统设置里,重启后会失效,如果永久添加可以用下面的命令来实现
ssh-add -K ~/.ssh/id_rsa_github
可以用开机运行脚本的方式,每次开机自动运行如下脚本。
实验的结果是,调用脚本会提示输入密码,所以并不能自动运行成功运行?
ssh-add ~/.ssh/id_rsa_github
ssh-add ~/.ssh/id_rsa_bitbucket
ssh-add ~/.ssh/id_rsa_oschina
你可以用 ssh-add -l
来查看一下添加效果,一般会出现下面的提示信息
2048 SHA256:ueU7NSaLTzfKNMKL3EVkBKqK2/bvr/ewdNVTmBYZtxg /Users/YourName/.ssh/id_rsa_github (RSA)
2048 SHA256:xGAMHLe5Un5LLWiXp6GI84CVn23sD9g+EQBjXMQP34YA /Users/YourName/.ssh/id_rsa_bitbucket (RSA)
2048 SHA256:lJfTU9j6JfkMSM4vJpk5BdsARzkRA/d05aUnc2BdBeg /Users/YourName/.ssh/id_rsa_oschina (RSA)
这就证明你之前添加都已经生效了。
当然如果这里出现什么问题,你也可以用 ssh-add -d
来删除某个 id_rsa
保存公钥到 git 服务
打开对应的git服务网站管理页面把对应的公钥提交保存到代码管理服务器( .pub
结尾)
添加 ssh 配置文件
在 ~/.ssh
目录创建 config 配置文件 (如果没有的话)
nano ~/.ssh/config
添加配置信息
Host github.com
HostName github.com
User git
IdentityFile /Users/YourName/.ssh/id_rsa_github
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile /Users/YourName/.ssh/id_rsa_bitbucket
Host oschina.net
HostName oschina.net
User git
IdentityFile /Users/YourName/.ssh/id_rsa_oschina
好了,这样你就可以任意穿梭于多个 git
服务器而不用担心 ssh key
的问题了。
注意,关于 ssh-add 持久化失效的问题,如果你的系统版本是 Sierra 10.12.2 以上,可以在 ~/.ssh/config
文件中增加如下代码,来实现持久化效果
Host *
UseKeychain yes