PERMISSION DENIED (PUBLICKEY).

A problem occurred when I tried to run git push to my Git server on EC2. The error looked like this:

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

The references I used while fixing it were:

  • <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/>

Set Up the SSH Client

First make sure the .ssh directory exists and has safe permissions:

mkdir -p ~/.ssh
chmod 700 ~/.ssh

If the failure is related to host key verification, add the remote host to known_hosts. For GitHub this would be:

ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
chmod 600 ~/.ssh/known_hosts

For your own Git server, replace github.com with the server’s domain name or IP address.

Next, generate an SSH key if you do not already have one:

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

This usually creates:

~/.ssh/id_rsa
~/.ssh/id_rsa.pub

Add the public key to the remote account that will receive your Git connection. For GitHub, add the contents of id_rsa.pub to the SSH keys list in your GitHub profile. For a self-hosted Git server, add the public key to the remote user’s ~/.ssh/authorized_keys file, or use:

ssh-copy-id -i ~/.ssh/id_rsa.pub USERNAME@SERVERNAME

Configure SSH to Use the Key

Edit your SSH config:

vim ~/.ssh/config

Add a host entry like this:

Host SERVERNAME
  HostName ip-or-domain-of-server
  User USERNAME
  PubkeyAuthentication yes
  IdentityFile ~/.ssh/id_rsa

Then make sure the config file has the correct permissions:

chmod 600 ~/.ssh/config

Start the SSH Agent

The sign_and_send_pubkey: signing failed: agent refused operation message can happen when the SSH agent is not running correctly or the key has not been loaded. Start the agent and add the key:

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

You can check which keys are loaded with:

ssh-add -l

Test the Connection

Before trying git push again, test SSH directly:

ssh -T git@github.com

For a self-hosted Git server, use the configured host:

ssh -T SERVERNAME

If the connection works, try the Git command again:

git push

If it still fails, check that the Git remote URL is using SSH rather than HTTPS:

git remote -v

An SSH remote usually looks like one of these:

git@github.com:USER/REPO.git
USERNAME@SERVERNAME:/path/to/repo.git

Once the key is loaded, the host is trusted, and the remote URL points to the correct SSH host, Permission denied (publickey) should be resolved.

Leave a Reply