0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SSH エージェント認証の不備による Git Push エラーの対処法

Posted at

発生した問題

GitHub で複数アカウントを使い分けている際、git push -u origin main コマンドを実行したところ、以下のような認証エラーが発生しました。

Permission to ○○○/repository.git denied to △△△

これは、意図したアカウント(○○○)ではなく、別のアカウント(△△△)で認証が試行されたことを示しています。

根本原因

SSH 設定ファイル(~/.ssh/config)では正しく複数アカウントの設定を行っていましたが、SSH エージェントに意図したアカウントの鍵が登録されていなかったため、デフォルトの鍵または別アカウント用の鍵が使用されていました。

問題の診断方法

  1. SSH 接続テスト

    $ ssh -T github-account-a
    
    Hi △△△! You've successfully authenticated, but GitHub does not provide shell access.
    

    → 期待していたアカウント(○○○)ではなく、別のアカウント(△△△)として認証されていることが判明

  2. SSH 設定の確認

    $ cat ~/.ssh/config
    Host github-account-a
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_github_account_a
      IdentitiesOnly yes
    

    → 設定自体は正しく行われていました

  3. SSH エージェントの状態確認

    $ ssh-add -l
    

    アカウントAの鍵が表示されていない

解決手順

  1. SSH エージェントに正しい鍵を追加
    $ ssh-add ~/.ssh/id_ed25519_github_account_a
    
    Identity added: ~/.ssh/id_ed25519_github_account_a
    

  2. 認証状態の再確認
    $ ssh -T github-account-a
    
    Hi ○○○! You've successfully authenticated, but GitHub does not provide shell access.
    
    → 正しいアカウント(○○○)での認証が確認できました

  3. Git コマンドの再実行
    $ git push -u origin main
    # 正常にプッシュ成功
    

恒久的な対策

1. 自動鍵登録の設定

シェルの起動スクリプト(.bashrc、.zshrc など)に以下を追加:

# GitHub アカウント用の SSH 鍵を自動追加
# -q: 静かに実行、2>/dev/null: エラーメッセージを非表示
ssh-add -q ~/.ssh/id_ed25519_github_account_a 2>/dev/null
ssh-add -q ~/.ssh/id_rsa_github_account_b 2>/dev/null

2. SSH 設定の最適化

~/.ssh/config ファイルに以下の設定を追加:

Host *
  AddKeysToAgent yes
  UseKeychain yes  # macOSの場合のみ

3. 作業前の認証確認習慣化

重要な操作の前に認証状態を確認する習慣をつける:

$ ssh -T github-account-a  # アカウントAの認証確認
$ ssh -T github-account-b  # アカウントBの認証確認

トラブルシューティングのポイント

  • SSH エージェントの状態は一時的: システム再起動やログアウトでリセットされることがあります
  • 複数アカウント使用時の注意点: 意図したアカウントで認証されているか常に確認が必要です
  • エラーメッセージの読み方: Permission denied to [username] の部分で、どのアカウントとして認証されようとしているかがわかります

まとめ

Git と SSH を使った複数アカウント管理では、SSH 設定だけでなく SSH エージェントの状態も重要です。認証エラーが発生した場合は、まず ssh -T コマンドで現在の認証状態を確認し、必要に応じて ssh-add で適切な鍵をエージェントに追加しましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?