Permission denied (publickey).

A problem occurred when I ran git push to my Git server on EC2:

sign_and_send_pubkey: signing failed: agent refused operation
Permission denied (publickey).
fatal: Could not read from remote repository.

I handled it by checking the Git remote URL, refreshing SSH host keys where necessary, and making sure the right SSH key was generated, loaded, and registered.

Original references I used:

  • <http://stackoverflow.com/questions/13363553/git-error-host-key-verification-failed-when-connecting-to-remote-repository>
  • <https://chenhuachao.com/2016/05/26/ssh%E5%87%BA%E9%94%99-sign-and-send-pubkey-signing-failed-agent-refused-operation/>

Sorry for missing the second source link before; I will add it later if I find it.

Check the remote URL

First, check whether your remote URL is correct:

git remote -v

If it is outdated or points to the wrong host, update it:

git remote set-url origin git://new.url.here

For SSH remotes, the URL usually looks more like this:

git remote set-url origin git@github.com:USER/REPO.git

or, for a private Git server:

git remote set-url origin USERNAME@SERVERNAME:/path/to/repo.git

Refresh known_hosts

If the error is related to host key verification, make sure ~/.ssh exists and add the server’s host key.

For GitHub:

mkdir -p ~/.ssh
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts

For your own server, replace github.com with your server name or IP address:

ssh-keyscan -t rsa SERVERNAME >> ~/.ssh/known_hosts

If you already have ~/.ssh/known_hosts, do not delete it unless you understand why the existing host key is wrong. If the host key changed unexpectedly, verify the server fingerprint before accepting the new one.

Generate an SSH key

Generate a key if you do not already have one:

ssh-keygen -t rsa -C "user.email"

The default public key path is usually:

~/.ssh/id_rsa.pub

Add the contents of that .pub file to the SSH keys list on your GitHub profile or to the authorized keys on your Git server.

For GitHub, you can print the public key with:

cat ~/.ssh/id_rsa.pub

Set up your client

  1. Generate your key:

“`bash
ssh-keygen
“`

  1. Configure SSH to use the key:

“`bash
vim ~/.ssh/config
“`

  1. Copy your key to your server:

“`bash
ssh-copy-id -i /path/to/key.pub SERVERNAME
“`

Your config file from step 2 should contain something similar to this:

Host SERVERNAME
    HostName ip-or-domain-of-server
    User USERNAME
    PubkeyAuthentication yes
    IdentityFile /path/to/key

Use an absolute path for IdentityFile, such as:

IdentityFile ~/.ssh/id_rsa

Load the key into ssh-agent

If you see this error:

sign_and_send_pubkey: signing failed: agent refused operation

start ssh-agent and add your key:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

Then test the SSH connection.

For GitHub:

ssh -T git@github.com

For your own server:

ssh -T SERVERNAME

After SSH authentication works, try the Git command again:

git push

Leave a Reply