45
35

More than 3 years have passed since last update.

git clone したら、Permission denied (publickey).のエラー

Last updated at Posted at 2020-03-02

事の発端

git clone したら、

Permission denied (publickey).
fatal: Could not read from remote repository.

とエラーが表示されました。

動作環境

クライアント側はMacOS
サーバ側はgithub

前置き

以下のサイトを見ても解決出来ない状況でした。
http://tusukuru.hatenablog.com/entry/2018/08/29/021651
結果として、鍵の設定自体は変更しないで解決できます。

~/.ssh/ のディレクトリの状況

.sshのディレクトリは、過去に別のサーバ等でsshの設定がいくつか存在しているので、以下のようになっています。

~/.ssh --- config         ←このconfigファイルを修正しましょう
        |- id_rsa_sample1
        |- id_rsa_sample1.pub
        |- id_rsa_sample2
        |- id_rsa_sample2.pub
        |- known_hosts

(先に書いておくと、秘密鍵の名前を id_rsa_sample1 から id_rsa に変更したくない。変更しないでエラーを解消したいということです。)
また、githubに2アカウント持っていて両方ともsshで接続したいという状況です。

~/.ssh/config の内容

以下のようにconfigファイルを設定して下さい。

host github-sample1
  hostname github.com
  IdentityFile ~/.ssh/id_rsa_github_sample1
  User sample1

host github-sample2
  hostname github.com
  IdentityFile ~/.ssh/id_rsa_github_sample2
  User sample2

ポイントは、host github-sample2のハイフンです。
host github-[ユーザ名] です。

実行したコマンドと、エラーの表示内容

$ git clone git@github.com:[アカウント名]/[リポジトリ名].git

Cloning into '[リポジトリ名]'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

エラー発生時の状況

$ ssh -T git@github-sample1 を実行しても
Hi sample1! You've successfully authenticated, but GitHub does not provide shell access.
と表示される (つまり、sshの接続はできている)のに、sshで git cloneでき〜ん。
ヽ(`Д´)ノ 「もうわからーん!!!」

エラーの原因

~/.ssh/config の設定でgithubに2アカウントでもログイン出来るようにするための設定をしていたため、git clone git@github.com:[アカウント名]/[リポジトリ名].git と実行したのが、sshで接続出来ない原因でした。

正解のコマンド

# ↓ これが正解
$ git clone git@github-sample2:[アカウント名]/[リポジトリ名].git

# ↓ これだとエラー
$ git clone git@github.com:[アカウント名]/[リポジトリ名].git

つまり、~/.ssh/config の内容を設定している場合、githubで標準で表示される以下のような
git clone git@github.com:[アカウント名]/[リポジトリ名].git
だと、タイトルのようなエラーが出る。

sshで接続する確認

$ ssh -T git@github-[アカウント名]
つまり
$ ssh -T git@github-sample2

Enter passphrase for key '/Users/xxxxx/.ssh/id_rsa_github': 
Hi sample2! You've successfully authenticated, but GitHub does not provide shell access.

このようにして、ssh接続の確認ができます。

まとめ

解決方法として、① ~/.ssh/config の内容を修正して 1アカウントのみでsshの設定を指定する、② $ git clone git@github .com ではなく、 git clone git@github-sample2 としてコマンドを実行する、③ 秘密鍵の名前を~/.ssh/id_rsa に変更するか、の3択だと思われます。

45
35
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
45
35