manager@mobile:~/.ssh$ ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/manager/.ssh/id_rsa): /home/manager/.ssh/testrepo_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/manager/.ssh/testrepo_rsa.
Your public key has been saved in /home/manager/.ssh/testrepo_rsa.pub.
The key fingerprint is:
...
查看刚生成的公钥
manager@mobile:~/.ssh$ cat ~/.ssh/testrepo_rsa.pub
ssh-rsa AAAAB3XXaC1yc2EAAAADAQABAAABAQChzWLBg6PF1raAA+XCip19Agp9PA7nkENj4MySZaJB6dXNfuKBjuwmOr/U3AChi+afJJ7vLCnEY4CakxPUIJfzHPHLrztG6uo31/s80APdJCc4K46aHXdM7CiJLNasZ9hvlj8xCECAq3WsQ8Li5uQ6CMPxTu1W0EEK1IO66Be6vCI33h/utFXr9Jqms2LRf8kU39N7KeiP8YFf58ltK4FN+B6+7mEmfhpsW726Ad0WBq872qIBLqaL9AQ5WO9/6tUgaeqKLKqox8EBabGHswhqoxpC4tymtceLFLu5yTZTZ/KbwCZttPP2pQID7AdmW/Z7xbhxrw4b8ciPgwnJq2bZ [email protected]
登录 gitlab 网站,点击你的用户头像,进入 Settings,点击左侧的 SSH Keys。
添加刚生成的公钥,添加标题,点击 Add key 按钮
vim ~/.ssh/config
添加类似如下几行
Host testrepo
HostName gitlab.abc.net
User git
IdentityFile ~/.ssh/testrepo_rsa
Host dxys
HostName gitlab.abc.net
User git
IdentityFile ~/.ssh/dxys_rsa
Host rn
HostName gitlab.abc.net
User git
IdentityFile ~/.ssh/rn_rsa
上面配置的意思:
当你希望克隆 [email protected]:tik5213/aspirin-release-manager.git 这个仓库时。你可以使用如下命令来克隆:
git clone testrepo:tik5213/aspirin-release-manager.git
ssh 会将 testrepo 替换成 [email protected] (即 HostName + User),
最终,使用 IdentityFile 中指明的 ~/.ssh/testrepo_rsa 私钥去请求下载目标仓库。
即:[email protected]:tik5213/aspirin-release-manager.git
我们要克隆的目录仓库是
[email protected]:tik5213/aspirin-release-manager.git
按照上面 ssh config 的配置,我们可以有如下两种方式来克隆此仓库
方式一:
git clone rn:tik5213/aspirin-release-manager.git
方式二:
git clone dxys:tik5213/aspirin-release-manager.git
但是,如果你想直接使用如下方式来克隆,很有可能你克隆不下来:
git clone [email protected]:tik5213/aspirin-release-manager.git
报错如下:
manager@mobile:~/.ssh$ git clone [email protected]:tik5213/aspirin-release-manager.git
Cloning into 'aspirin-release-manager'...
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
此时,你可以在 ssh config 中添加如下配置:
Host gitlab.abc.net
HostName gitlab.abc.net
User git
IdentityFile ~/.ssh/rn_rsa
当然,你也可以简单的写作:
Host gitlab.dxy.net
IdentityFile ~/.ssh/rn_rsa
或者,更简单的写作;
Host *
IdentityFile ~/.ssh/rn_rsa
一般的,你应当将更需要通配性质的 host (比如 *),放到 ssh config 的最后面。