LoginSignup
11
14

More than 5 years have passed since last update.

1台のPCで複数のGithubアカウントを使い分ける

Last updated at Posted at 2017-04-16

仕事用、自分用というように複数アカウントを持っていて1台のPCで使い分けたい場合に見るメモです。

背景

もともと1台のPCでアカウントAはSSH、アカウントBをHTTPSで使用していました。
が、何か変な操作したのかアカウントBでpushする時にアカウントAで認証しにいくようになってしまい、アカウントBがHTTPSで使えなくなってしまいました。
解決方法がわからず、両方SSHにしてしまえと思ったのが事の始まりです。

前提

  • アカウントAはすでに設定も終えて使えている状態である
  • Macでの手順である

手順

  1. アカウントBのSSHキーを発行
  2. アカウントBのSSHキーをGithubに登録
  3. ~/.ssh/configを作成
  4. アカウントBのリポジトリの設定

1.アカウントBのSSHキーを発行

まずは既存のSSHキーファイル名を確認。

$ cd ~/.ssh
$ ls
id_rsa id_rsa.pub

ファイル名を被らないように、アカウントBのSSHキーを作成。

# 例:ssh-keygen -t rsa -C username@email.com -f id_rsa.accountB
$ ssh-keygen -t rsa -C [アカウントBのemail address] -f [file name]

2.アカウントBのSSHキーをGithubに登録

Githubのヘルプ参照
https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/

3. ~/.ssh/config を作成

最低限以下を設定すれば良さそう。

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa
    Port 22
Host github.com.sub
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa.accountB
    Port 22
項目 設定値
Host アカウントA、アカウントBを識別できる名前
HostName github.comを設定
User gitを設定
IdentitiyFile それぞれのアカウントのキーファイルを設定
Port 22を設定

4. SSHキーの登録

アカウントBのSSHキーを登録する。

$ ssh-add /Users/your_home/.ssh/id_rsa.accountB
Enter passphrase for /Users/your_home/.ssh/id_rsa.accountB: # githubのログインパス
Identity added: /Users/your_home/.ssh/id_rsa.accountB (/Users/your_hoe/.ssh/id_rsa.accountB)

それぞれのHost名で接続確認しよう。

$ ssh -T github.com
Hi アカウントA! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T github.com.sub
Hi アカウントB! You've successfully authenticated, but GitHub does not provide shell access.

※ Hi ~ のところが両方同じアカウント名の場合どこかがおかしいです。

5.アカウントBのリポジトリの設定

リポジトリ毎に設定が必要なので少し手間、でもしょうがない。
アカウントBのリポジトリへ移動し、名前とメールアドレスを設定しよう。

$ cd アカウントBのリポジトリ
$ git config user.name "アカウントBのユーザーネーム"
$ git config user.email "アカウントBのメールアドレス"

リモートのURLを設定する。

# 例:git remote add origin git@github.com.sub:accountB/repository.git
$ git remote add origin git@[アカウントBのHost]:[アカウントB]/[repository name].git

# 例:git remote set-url origin git@github.com.sub:accountB/repository.git
$ git remote set-url origin git@[アカウントBのHost]:[アカウントB]/[repository name].git

いじょ。

11
14
1

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
11
14