使用環(huán)境:
- 關(guān)于同一臺Mac電腦下使用多個SSH key 切換使用(或者多用戶使用ssh提交代碼)
- 既可以提交代碼到github,也可以提交代碼到oschina,提交的時候都走ssh協(xié)議,但是默認(rèn)情況下只能有一個ssh key(~/ssh)
生成公鑰、私鑰
$ ssh-keygen -t rsa -C "your_github_email@example.com"
保存到 `~/.ssh/id_rsa_github`
$ ssh-keygen -t rsa -C "your_oschina_email@example.com"
保存到 `~/.ssh/id_rsa_oschina`
配置ssh代理
// 查看系統(tǒng)ssh-key代理
$ ssh-add -l
// 如果系統(tǒng)已經(jīng)有ssh-key 代理 ,執(zhí)行下面的命令可以刪除
$ ssh-add -D
// 把 ~/.ssh 目錄下的2個私鑰添加的 ssh-agent
$ ssh-add ~/.ssh/id_rsa_github
$ ssh-add ~/.ssh/id_rsa_oschina
// 在 .ssh 目錄創(chuàng)建 config 配置文件
$ vim ~/.ssh/config
# github 配置
Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
# oschina配置
Host oschina
HostName git.oschina.net
User git
IdentityFile ~/.ssh/id_rsa_oschina
or
#aaa (github 配置)
Host aaa
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_aaa
#bbb (開源中國 配置)
Host bbb
HostName git.oschina.net
User git
IdentityFile ~/.ssh/id_rsa_bbb
#ccc
........
記住上面一步 Host 里設(shè)置的別名
驗證
// 查看ssh-key代理,會看到2條記錄
$ ssh-add -l
// 訪問github
$ ssh -T git@github.com
Hi 用戶名! You have successfully authenticated, but GitHub does not provide shell access.
// 訪問oschina
$ ssh -T git@git.oschina.net
Welcome to Git@OSC, 用戶名!
or
// 訪問aaa
$ ssh -T aaa
連接失敗 (Permission denied (publickey).)
$ ~ ssh -T papillon
The authenticity of host 'gitlab.com (52.167.219.168)' can't be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'gitlab.com,52.167.219.168' (ECDSA) to the list of known hosts.
Authentication failed.
$ ~ ssh -T git@gitlab.com
Permission denied (publickey).
ssh-agent
# 開啟 agent
$ eval $(ssh-agent -s) ←┘
Agent pid 8428
# 添加 鑰匙名
$ ssh-add ~/.ssh/id_rsa_github ←┘
Identity added: /c/Users/user/.ssh/id_rsa_github (/c/Users/user/.ssh/id_rsa_github)
# 查看 agent list
$ ssh-add -l ←┘
8428 SHA256:A9UcJMadwTpF7TvsT5LEXsSssTs5qehmV9Q2Q8Ntw3o /c/Users/user/.ssh/id_rsa_github (RSA)
# 不用時可以關(guān)閉 agent
$ eval $(ssh-agent -k) ←┘
Agent pid 8428 killed
原因是,我們自定義了 id_rsa_github 鑰匙名,默認(rèn)情況下,連接會搜索 id_rsa 鑰匙名,所以這里會失敗
可以通過 ssh -T -v git@github.com 了解連接失敗的具體原因
還有一種簡單的辦法,直接刪除id_rsa鑰匙名,全部使用帶有后綴的格式來寫
$ .ssh ls
config id_rsa.pub id_rsa_gat.pub id_rsa_papillon.pub
id_rsa id_rsa_gat id_rsa_papillon known_hosts
$ .ssh rm id_rsa id_rsa.pub