LoginSignup
8
9

More than 5 years have passed since last update.

複数GitHubアカウントに対応したSSH認証キー設定(Mac用)

Last updated at Posted at 2015-11-03

はじめに

GitHubのアカウントを複数持っている場合、(例えばプライベートと仕事用など)
リポジトリ毎に使用するアカウントを指定したい事があると思います。
それ、SSHの設定をすれば簡単にできちゃうんです。

SSH認証キー作成

ssh-keygen -C "yourmail@example.com" -f ~/.ssh/github-your-github-name

上述のyour-github-nameの部分はGitHubアカウントの名前が入ります。

パスフレーズは入力した方がセキュアです。
ただしパスフレーズを設定した場合後述の問題が発生する場合があります。

これを利用したいGitHubアカウント分用意します。

GitHubへ公開鍵を登録

  1. https://github.com/settings/ssh を開いてAdd SSH Keyボタンを押します
  2. Titlegithub-your-github-nameを入力します。
  3. Key~/.ssh/github-your-github-name.pubの内容を入力します。
pbcopy < ~/.ssh/github-your-github-name.pub

で~/.ssh/github-your-github-name.pubの内容をクリップボードにコピーできます(Mac限定)
4. 入力が終わったらAdd Keyを押して完了です。
5. これを利用したいGitHubアカウント分繰り返します。

.ssh/configの設定

Host github-your-github-name
    User git
    HostName github.com
    IdentityFile ~/.ssh/github-your-github-name
    TCPKeepAlive yes
    IdentitiesOnly yes

上記をGitHubアカウント分~/.ssh/configに追記します。

アクセステスト

無事設定が終わったらアクセステストをしてみましょう。

ssh github-your-github-name -v

うまくいけば、

(中略)
Hi your-github-name! You've successfully authenticated, but GitHub does not provide shell access.
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
Connection to github.com closed.
Transferred: sent 3448, received 2008 bytes, in 0.8 seconds
Bytes per second: sent 4232.6, received 2464.9
debug1: Exit status 1

と表示されるはずです。

gitリポジトリのclone

git clone git@github-your-github-name:NameOrTeam/Repository.git

your-github-nameにはそのリポジトリにアクセスしたいGitHubアカウントが入ります。
NameOrTeam/Repository.gitにはGitHubのリポジトリ名が入ります

既存のリポジトリをアカウント毎のSSH接続に切り替える

cd YourRepos
git remote show origin

としたとき

* remote origin
  Fetch URL: https://github.com/NameOrTeam/Repository.git
  Push  URL: https://github.com/NameOrTeam/Repository.git

* remote origin
  Fetch URL: git@github.com:NameOrTeam/Repository.git
  Push  URL: git@github.com:NameOrTeam/Repository.git

と表示されている場合アカウント毎の設定になっていません。

git remote set-url origin git@github-your-github-name:NameOrTeam/Repository.git

とすることで指定のアカウントに切り替えが可能です。
正しく設定されれば、git remote show originしたとき

* remote origin
  Fetch URL: git@github-your-github-name:NameOrTeam/Repository.git
  Push  URL: git@github-your-github-name:NameOrTeam/Repository.git

と表示されるはずです。

ログイン直後にSourceTree等でリポジトリにアクセスできない場合

SSH認証キーにパスフレーズが設定されている場合、
SourceTree等を使ってFetchしたときにサーバに接続できない場合があります。

ssh-add github-your-github-name

を試してみてください。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9