コンテンツにスキップ

GitHubのSSH設定

複数のGitHubアカウント(個人用と業務用など)を使い分けるためのSSH設定を行います。

Terminal window
# ディレクトリ作成
mkdir -p ~/.ssh/github
# SSH鍵生成
ssh-keygen -t rsa -b 4096 -C "your.personal@email.com" -f ~/.ssh/github/id_github_personal_rsa
Terminal window
# SSH鍵生成
ssh-keygen -t rsa -b 4096 -C "your.work@email.com" -f ~/.ssh/github/id_github_work_rsa

~/.ssh/configファイルを編集:

Terminal window
code ~/.ssh/config

以下の内容を追加:

# 個人用GitHubアカウント
Host github
HostName github.com
IdentityFile ~/.ssh/github/id_github_personal_rsa
User git
Port 22
TCPKeepAlive yes
IdentitiesOnly yes
# 業務用GitHubアカウント
Host github-work
HostName github.com
IdentityFile ~/.ssh/github/id_github_work_rsa
User git
Port 22
TCPKeepAlive yes
IdentitiesOnly yes
Terminal window
# 個人用
pbcopy < ~/.ssh/github/id_github_personal_rsa.pub
# 業務用
pbcopy < ~/.ssh/github/id_github_work_rsa.pub
  1. GitHubにログイン
  2. Settings → SSH and GPG keys
  3. “New SSH key”をクリック
  4. タイトルを入力し、公開鍵を貼り付け
  5. “Add SSH key”をクリック
Terminal window
# 個人用アカウント
ssh -T github
# 業務用アカウント
ssh -T github-work

成功すると以下のようなメッセージが表示されます:

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

個人用アカウントのリポジトリ

Section titled “個人用アカウントのリポジトリ”
Terminal window
git clone github:username/repository.git

業務用アカウントのリポジトリ

Section titled “業務用アカウントのリポジトリ”
Terminal window
git clone github-work:organization/repository.git

既存リポジトリのリモート設定変更

Section titled “既存リポジトリのリモート設定変更”

すでにクローンしたリポジトリのリモートURLを変更する場合:

Terminal window
# 現在のリモートURL確認
git remote -v
# 個人用に変更
git remote set-url origin github:username/repository.git
# 業務用に変更
git remote set-url origin github-work:organization/repository.git

特定のプロジェクトで異なるユーザー情報を使用する場合:

Terminal window
# プロジェクトディレクトリで実行
git config user.name "Your Name"
git config user.email "your.email@example.com"
  1. SSH鍵が正しく生成されているか確認
  2. GitHubに公開鍵が登録されているか確認
  3. SSH設定ファイルのパスが正しいか確認
Terminal window
# ssh-agentを起動
eval "$(ssh-agent -s)"
# 鍵を追加
ssh-add ~/.ssh/github/id_github_personal_rsa
ssh-add ~/.ssh/github/id_github_work_rsa
  • SSH鍵にはパスフレーズを設定する
  • 定期的に鍵を更新する
  • 不要になった鍵はGitHubから削除する