关于一台电脑配置多个ssh密钥

之前在自己电脑上配置了GitHub的ssh,实习时需要再配置另一个,配置完成之后发现无法git clone,解决方法在此记录。

问题

常规

  • ssh-keygen -t rsa -C xxx@mail.com生成rsa文件;
  • 复制id_rsa.pub文件中的pub key,添加到github或者对应的git网站中;
  • git clone ssh://git@github.com/xx/xxxxxxx

问题

如上,再重新添加一个时,

  • ssh-keygen -t rsa -C xxx@companymail.com生成另一个id_rsa_company,注意这一步自定义时换一下名称;

  • 同上第二步

  • git clone ssh://git@git.company.com/xx/xxxxxxx时却发现报错

    1
    2
    3
    4
    xxxxxxxxxxxxxxxx
    git@git.company.com: Permission denied (publickey).
    fatal: Counld not read from remote repository.
    xxxxxxxxxxxxxxxx

解决

对于一台电脑配置多个ssh密钥的解决方法:

  • ssh-keygen -t rsa -C "123456@qq.com" -f ~/.ssh/id_rsa
    ssh-keygen -t rsa -C "654321@qq.com" -f ~/.ssh/id_rsa_1
    
    1
    2
    3
    4

    * 对应git网站中分别添加上述生成的`id_rsa.pub`中内容即可

    * 在存放上述两个`id_rsa`文件的目录下`touch config`新建一个config文件并加入一下内容
    # git@github.com Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa # git@git.company.com Host git.company.com HostName git.company.com User git IdentityFile ~/.ssh/id_rsa_1 ...
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    * 再进行`git clone ssh://git@git.company.com/xx/xxxxxxx`成功。



    # 另

    1. 删除本地全局设置

    如果之前设置过`git config -global user.name` 和 `user.email`可能就需要用`git config -global unset user.name` 和 `user.email`删除掉,或者直接把用户目录下的.gitconfig文件删除,然后为每个仓库设置独立的用户名和邮箱,就是在仓库里面用上面的命令不要global选项

    2. **配置全局信息**
    $ git config --global user.name "Firstname Lastname" $ git config --global user.email "your_email@example.com"
    1
    2

    这个命令会在`~/.gitconfig`填入以下信息:
    [user] name = Firstname Lastname email = your_email@example.com
    1
    2
    3
    4

    如果需要修改信息,直接修改这个文件即可。

    **配置单独信息**
    $ cd your_project $ git config user.name "Firstname Lastname" $ git config user.email "your_email@example.com"

    这个命令会在项目目录下输出文件:/.git/.config

    这里设置的姓名和邮箱地址会用在 Git 的提交日志中。

:转载文章请注明出处,谢谢~