LoginSignup
1
0

More than 3 years have passed since last update.

【メモ】GitHubのアカウントを切り替える

Posted at

既出でしょうが、自分用メモ。

やりたいこと

社内用アカウントと個人のアカウント等、複数アカウントを切り替える必要がある場合に、一つの端末で複数のアカウントを使用したい。

準備

ssh認証の設定

メインアカウント、サブアカウントの両方にssh keyを登録します。

sshキーの作成

まず、GitHubのSSH認証の設定に用いる公開鍵と秘密鍵のペアを生成します。

$ ssh-keygen -t rsa
Enter file in which to save the key (C:\Users\username/.ssh/id_rsa):

なんて聞かれるので適当なお名前を付けておきましょう。
ここでは「id_rsa_git」とします。

Enter file in which to save the key (C:\Users\username/.ssh/id_rsa):C:\Users\username/.ssh/id_rsa_git

もしくは ディレクトリ.sshにいる状態で

Enter file in which to save the key (C:\Users\username/.ssh/id_rsa):id_rsa_git

こんな感じでいいと思います。

あとは適用にパスフレーズを入力し(入力しなくてもok)、

key fingerprintや、RSA 2048の夜空のようなimageが表示されれば成功です。

GitHubに公開鍵の登録

GitHubの個人設定ページへ行きます。

image.png

「SSH and GPG keys」の項目でSSH keyの登録ができます。

image.png

適当にtitleを付けて、先ほど生成したssh keyの.pubがついてるほう(公開鍵)の内容をKeyにつっこみましょう。

202007291106.png

これでメインアカウントのSSH認証の設定が完了です。

同様にして再度ssh keyを生成し、サブアカウントの方にもSSH keyの設定をしておきましょう。

ここで、先ほど生成したkeyと名前がかぶったりしないように命名を変えておくことに気を付けましょう。

Enter file in which to save the key (C:\Users\username/.ssh/id_rsa):C:\Users\username/.ssh/id_rsa_git_sub

ディレクトリを分けるのも個人的にアリだと思います。(.ssh/configをちゃんと記述しないと認識してくれないので、そこだけ注意)

Enter file in which to save the key (C:\Users\username/.ssh/id_rsa):C:\Users\username/.ssh/git_sub/id_rsa

アカウント分けるための設定

無事アカウントの設定が完了したら、アカウントごとのssh認証の設定を行います。

Hostについての~/.ssh/configファイルの作成

.ssh直下に以下の内容のファイルを置いておきましょう。

Host github.com                       # メインアカウントに関する記述
  HostName github.com 
  User git
  Port 22
  IdentityFile ~/.ssh/id_rsa_sub      # メインアカウントに登録している公開鍵に対応した秘密鍵
  TCPKeepAlive yes
  IdentitiesOnly yes
Host github.com.sub                   # サブアカウントに関する記述
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_rsa_git_sub  # サブアカウントに登録している公開鍵に対応した秘密鍵
  TCPKeepAlive yes
  IdentitiesOnly yes

ちゃんと設定できているか確認します。以下のコマンドを実行。

$ ssh -T git@github.com       # メイン
$ ssh -T git@github.com.sub   # サブ

こんなメッセージが返ってきたらうまくいってます。

Hi (username)! You've successfully authenticated, but GitHub does not provide shell access.

ディレクトリごとにユーザー情報の設定

以下コマンドでリモートのホストをリポジトリに対応するものに変更します。

$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git     # メイン
$ git remote set-url origin git@github.com.sub:USERNAME/REPOSITORY.git # サブ

アカウント情報(~/.gitconfig)の設定

最後にcommit等に残るアカウント情報の設定を行います。

自分はよく使う方のアカウントはglocalで登録しておいて

git config --global user.name {main_username}
git config --global user.email {main_useremail}

あんま使わないほうはリポジトリごとに登録したりしています。

git config --local user.name {sub_username}
git config --local user.email {sub_useremil}

以上でいい感じにアカウントの使い分けができると思います。やったね。

余談

TypeScriptの記事書きたいけど全然かけへん。。
もっと使いこなしたいね。

参考になりそうな記事

ssh認証の設定について詳しく書いてくれてる記事:
https://qiita.com/shizuma/items/2b2f873a0034839e47ce

1
0
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
1
0