LoginSignup
331
271

More than 3 years have passed since last update.

[備忘] 複数Githubアカウントでssh接続設定(config)を使い分ける手順

Last updated at Posted at 2017-09-09

会社用とプライベート用など、複数のGithubアカウントを使い分ける際の設定方法をまとめました。

ssh鍵を作成する

まず、ssh接続に使用する鍵をローカル環境で作成します。使用したいアカウント毎に、以下のコマンドで鍵ペアを作成します。

bash
cd ~/.ssh
ssh-keygen -t rsa -C {Githubメールアドレス} -f {作成する鍵の名前}

パスフレーズを設定する為、任意の文字列を2回入力します。
実行後、秘密鍵(ファイル名)と公開鍵(ファイル名.pub)が作成されます。

ssh設定ファイル(~/.ssh/config)の編集

アカウント毎にssh鍵を使い分ける為、ローカル環境のssh設定ファイルにHost(接続元)の登録を行います。

ssh設定ファイル~/.ssh/configを以下の通り書き換えます(存在しない場合は作成)。
今回はmainとsubでアカウントを切り替える為、2つのHostを登録します。
項目IdentityFileに、それぞれのアカウントで使用する秘密鍵のパスを指定します。

~/.ssh/config
Host github.com.main # メインアカウント
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_rsa_main  # メインアカウント用の鍵
  TCPKeepAlive yes
  IdentitiesOnly yes

Host github.com.sub # サブアカウント
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_rsa_sub  # サブアカウント用の鍵
  TCPKeepAlive yes
  IdentitiesOnly yes

Githubに公開鍵を登録する

作成した公開鍵をGithubに登録します。

Githubにログインして、[Settings] -> [SSH keys] -> [Add SSH key]で作成した公開鍵を登録します。(詳細はこちらを参照)

ssh接続確認

ssh設定ファイルに登録したHostで、正しくssh接続ができることを確認します。

bash
ssh -T git@github.com.main
ssh -T git@github.com.sub

秘密鍵のパスフレーズを聞かれるので、正しく入力すると以下のメッセージが返ってきます。

bash
Hi {yourname}! You've successfully authenticated, but GitHub does not provide shell access.

cloneする

リポジトリをcloneをする際には、ssh設定ファイルに登録したHostを指定します。

bash
# (メインアカウントを使う場合:)
git clone git@github.com.main:username/repository-name.git

git remote add origin git@github.com.main:username/repository-name.git

以下のコマンドでgitのurlが正しく設定されているか確認します。

bash
git config remote.origin.url

git@github.com.xxx:~のxxxの部分が~/.ssh/configに設定したHost名になっていればOKです。今後gitコマンドではHostで設定したssh鍵が使用されます。

git設定ファイル(gitconfig)の設定

ここまでsshの鍵を設定しましたが、gitのユーザー名も設定する必要があります。以下を設定します。

普段使う名前は、以下のコマンドでglobalに設定しておきます。
~/.gitconfigを直接編集してもOK)

bash
git config --global user.name {ユーザー名}
git config --global user.email {メールアドレス}

リポジトリ毎ににユーザ名を切り替える場合、以下を実行します。
{リポジトリのパス}/.git/configを直接編集してもOK)

bash
cd {リポジトリ名}
git config --local user.name {ユーザー名}
git config --local user.email {メールアドレス}

参考

331
271
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
331
271