[TOC]
摘要
实现效果:不同账号配置不同的密钥,不同仓库配置不同密钥。
背景知识
Git共有三个级别的config文件,分别是:
- system :%GitPath%\mingw64\etc\gitconfig文件
- global:$home.gitconfig文件
- local:%RepoPath%.git\config文件
其中%GitPath%
为Git的安装路径,%RepoPath%
为某仓库的本地路径。
所以 system 配置整个系统只有一个,global 配置每个账户只有一个,而 local 配置和git仓库的数目相同,并且只有在仓库目录才能看到该配置。
实现
生成新的 SSH keys
ssh-keygen
默认的加密方式为:rsa
在配置多账号时需要生成不同的密钥并保存在不同文件中加以区分,故需要指定保存的文件
方式一:在提示中输入
Think@DESKTOP-NNP5G5O MINGW64 ~/.ssh
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/Think/.ssh/id_rsa): id_rsa.gitee
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa.gitee.
Your public key has been saved in id_rsa.gitee.pub.
The key fingerprint is:
SHA256:4iLlxBGWXvD+34COmT1J6EdbP/hv9TC/D2g4obsDiNs Think@DESKTOP-NNP5G5O
The key's randomart image is:
+---[RSA 2048]----+
| +o |
| ..o. |
| .... |
| ..o |
| .+.o.S . |
| .+..oooo.o .o .|
| .oo..++++oo .=.|
| ..E..**o.=o ..o|
| +.=+..o+..+|
+----[SHA256]-----+
方式二:在执行命令中传入参数
ssh-keygen -t rsa -f ~/.ssh/id_rsa.gitee -C "你的邮箱"
完成后会在~/.ssh / 目录下生成以下文件:
- id_rsa.github
- id_rsa.github.pub
- id_rsa.gitee
- id_rsa.gitee.pub
添加识别 SSH keys 新的私钥
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa.github
$ ssh-add ~/.ssh/id_rsa.gitee
多账号必须配置 config 文件(重点)
创建config文件
$ touch ~/.ssh/config
配置内容
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa.gitee
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa.github
下面对上述配置文件中使用到的配置字段信息进行简单解释:
- Host 它涵盖了下面一个段的配置,我们可以通过他来替代将要连接的服务器地址。 这里可以使用任意字段或通配符。 当ssh的时候如果服务器地址能匹配上这里Host指定的值,则Host下面指定的HostName将被作为最终的服务器地址使用,并且将使用该Host字段下面配置的所有自定义配置来覆盖默认的/etc/ssh/ssh_config配置信息。
- Port 自定义的端口。默认为22,可不配置
- User 自定义的用户名,默认为git,可不配置
- HostName 真正连接的服务器地址
- PreferredAuthentications 指定优先使用哪种方式验证,支持密码和秘钥验证方式
- IdentityFile 指定本次连接使用的密钥文件
在 github 和 gitee 添加 ssh
拷贝的~/.ssh/id_rsa.xxx.pub
文件内容粘帖到 key 一栏,确定即可
测试连接
下面是连接成功的响应:
Think@DESKTOP-NNP5G5O MINGW64 ~/.ssh
$ ssh -T git@github.com
Hi yourname! You've successfully authenticated, but GitHub does not provide shell access.
Think@DESKTOP-NNP5G5O MINGW64 ~/.ssh
$ ssh -T git@gitee.com
Hi yourname! You've successfully authenticated, but GITEE.COM does not provide shell access.
问题
tilde_expand_filename: No such user
报错:
$ ssh -T git@github.com
tilde_expand_filename: No such user .
解决:
此问题是因为写错了文件路径
或者 大小写没写对
,删除重新配置。