一個指令切換預設使用的 SSH Key

因應公司和個人有分開的 github 帳號,為了能在同一台電腦同使用者內工作,已經幾次重複解決這個問題,故寫篇文章記錄之。

檢視現在使用的 SSH Key

我們可以使用 ssh-add 這個工具來檢視目前使用 ssh 指令連線時,會使用的 ssh key:

$ ssh-add -l
3072 SHA256:******************/****************** my-default-email@dwye.dev (RSA)

也可以直接用 ssh -T,使用 ssh 連線但不要使用虛擬終端(pty)
這也衍生了 github 使用 git 這個 user,作為設置 ssh key 時常見的確認手段:

$ ssh -T git@github.com
Hi your-account! You've successfully authenticated, but GitHub does not provide shell access.

SSH Key 的切換

ssh-add 顧名思義也可以用來管理 ssh-agent 現在使用的 ssh-key。

加入一個 ssh key:

$ ssh-add ~/.ssh/my_rsa
Identity added: /Users/myaccount/.ssh/my_rsa (my-default-email@dwye.dev)

清空 ssh key:

$ ssh-add -D
All identities removed.

因此我們就可以做如此操作達到切換 ssh key 的效果:

# ~/switch_main.sh
ssh-add -D
ssh-add ~/.ssh/id_rsa
# ~/switch_personal.sh
ssh-add -D
ssh-add ~/.ssh/my_rsa

然後在啟動 shell 時加入 alias 即可

# ~/.bashrc 或是 ~/.zshrc
alias gitp='source ~/switch_personal.sh'
alias gitm='source ~/switch_main.sh'

之後就可以在 terminal 中透過 gitpgitm 一指令切換 ssh key 了。

8/5 更新

是的,才寫完這篇沒多久馬上就找到新解法來切換 git 使用的 ssh key,就不用每次開 shell 都要去手動改了(變成 0 指令切換 XD),我也比較喜歡這個新解法,詳細請見客製化 git 使用的 SSH Key