GitHubのSSH設定
複数のGitHubアカウント(個人用と業務用など)を使い分けるためのSSH設定を行います。
SSH鍵の生成
Section titled “SSH鍵の生成”個人用アカウント
Section titled “個人用アカウント”# ディレクトリ作成mkdir -p ~/.ssh/github
# SSH鍵生成ssh-keygen -t rsa -b 4096 -C "your.personal@email.com" -f ~/.ssh/github/id_github_personal_rsa業務用アカウント
Section titled “業務用アカウント”# SSH鍵生成ssh-keygen -t rsa -b 4096 -C "your.work@email.com" -f ~/.ssh/github/id_github_work_rsaSSH設定ファイルの編集
Section titled “SSH設定ファイルの編集”~/.ssh/configファイルを編集:
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 yesGitHubへの公開鍵の登録
Section titled “GitHubへの公開鍵の登録”公開鍵をコピー
Section titled “公開鍵をコピー”# 個人用pbcopy < ~/.ssh/github/id_github_personal_rsa.pub
# 業務用pbcopy < ~/.ssh/github/id_github_work_rsa.pubGitHubに登録
Section titled “GitHubに登録”- GitHubにログイン
- Settings → SSH and GPG keys
- “New SSH key”をクリック
- タイトルを入力し、公開鍵を貼り付け
- “Add SSH key”をクリック
# 個人用アカウントssh -T github
# 業務用アカウントssh -T github-work成功すると以下のようなメッセージが表示されます:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.リポジトリのクローン
Section titled “リポジトリのクローン”個人用アカウントのリポジトリ
Section titled “個人用アカウントのリポジトリ”git clone github:username/repository.git業務用アカウントのリポジトリ
Section titled “業務用アカウントのリポジトリ”git clone github-work:organization/repository.git既存リポジトリのリモート設定変更
Section titled “既存リポジトリのリモート設定変更”すでにクローンしたリポジトリのリモートURLを変更する場合:
# 現在のリモートURL確認git remote -v
# 個人用に変更git remote set-url origin github:username/repository.git
# 業務用に変更git remote set-url origin github-work:organization/repository.gitプロジェクトごとのGit設定
Section titled “プロジェクトごとのGit設定”特定のプロジェクトで異なるユーザー情報を使用する場合:
# プロジェクトディレクトリで実行git config user.name "Your Name"git config user.email "your.email@example.com"トラブルシューティング
Section titled “トラブルシューティング”Permission denied (publickey)エラー
Section titled “Permission denied (publickey)エラー”- SSH鍵が正しく生成されているか確認
- GitHubに公開鍵が登録されているか確認
- SSH設定ファイルのパスが正しいか確認
ssh-agentの使用
Section titled “ssh-agentの使用”# ssh-agentを起動eval "$(ssh-agent -s)"
# 鍵を追加ssh-add ~/.ssh/github/id_github_personal_rsassh-add ~/.ssh/github/id_github_work_rsaセキュリティ推奨事項
Section titled “セキュリティ推奨事項”- SSH鍵にはパスフレーズを設定する
- 定期的に鍵を更新する
- 不要になった鍵はGitHubから削除する