拥有多个github账号时,如何管理多个SSH key?


目前github已经拒绝通过密码访问私有仓库,只能通过SSH Key。但SSH key不能重复使用,如果有多个github账号的话,就需要多个不同的key。
如果访问一个私有仓库的话,出现如下提示,则说明可能当前的key不正确。那么如何管理多个key就成为一个问题。
$ git clone git@github.com:lylhw13/some_repository.git
Cloning into some_repository...
ERROR: Repository not found.
fatal: Could not read from remote repository.

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

下面有两个方案管理多个key:

    通过ssh-add单次添加 通过config配置,设置多次添加

预备:生成一个新的SSH Key

输入以下指令,并将邮箱替换为自己的邮箱

$ ssh-keygen -t ed25519 -C "your_email@example.com"

在如下提示中设定自己的的文件名,为了避免和默认key 冲突,需要指定一个新的名称,如果不存在默认key,直接回车:

Enter file in which to save the key (~/.ssh/id_ed25519): ~/.ssh/id_ed25519_personal

使用默认密钥,直接两次回车即可。 将 ~/.ssh/id_ed25519_personal.pub 注册到github账户上。

单次添加

如果只是偶尔使用一个key,可以通过ssh-add 单次添加。如下命令。

$ eval `ssh-agent -s`
$ ssh-add ~/.ssh/id_ed25519_personal

该方案缺点在于,每一个新的窗口都需要添加一次。 注:在执行ssh-add时,必须如上面先执行evel命令,否则会出现如下错误提示:

Could not open a connection to your authentication agent.

永久添加

配置

通过config ,可以记录不同host和不同key的映射关系。

$ sudo vim ~/.ssh/config

添加如下内容:

Host git_personal
        HostName github.com
        Identityfile ~/.ssh/id_ed25519_personal
    Host 的名称可以任意,只要方便记忆即可 HostName 这里写为 github.com Identityfile 这里指向刚生成的key。

测试配置是否正确

执行如下指令

$ ssh -T git@git_personal

如果输出如下结果,代表配置正确:

Hi lylhw13! Youve successfully authenticated, but GitHub does not provide shell access.

如果输出以下结果,代表github账号没有添加该key文件:

git@github.com: Permission denied (publickey).

使用

这样在我们使用git命令,比如clone 的时候,将如下地址的github.com替换为git_personal即可,这样git便会通过config找到正确的key文件:

$ git clone git@github.com:lylhw13/code_job.git

修改为

$ git clone git@git_personal:lylhw13/code_job.git

参考:

经验分享 程序员 微信小程序 职场和发展