[git] How to solve Permission denied (publickey) error when using Git?

I'm on Mac Snow Leopard and I just installed git.

I just tried

git clone [email protected]:cakebook.git

but that gives me this error:

Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

What am I missing?
I've also tried doing ssh-keygen with no passphase but still same error.

This question is related to git ssh ssh-keys public-key

The answer is


This works for me:

ssh-add ~/.ssh/id_rsa

It worked for me.

Your public key is saved to the id_rsa.pub;file and is the key you upload to your account. You can save this key to the clipboard by running this:

pbcopy < ~/.ssh/id_rsa.pub

  • copy the SSH key to the clipboard, return to the web portal.
  • In the SSH Key field, paste your SSH key.
  • In the Name field, provide a name for the key.
  • save .

I had a slight different situation, I was logged on to a remote server and was using git on the server, when I ran any git command I got the same message

   Permission denied (publickey).
   fatal: The remote end hung up unexpectedly

The way I fixed it was by changing the file /etc/ssh_config on my Mac. from

ForwardAgent no 

to

ForwardAgent yes

Use the ssh link from Github but make sure to not append it with ssh just use what the ssh tab on git hub gives you to clone your repo.


In my MAC I solved this with:

cp ~/.ssh/github_rsa ~/.ssh/id_rsa

For some reason my git stopped to find the private key in the github_rsa file. This happened in a specific repo. I mean that in other repositories git kept working normally.

I think it's a bug.

I could find this behavior running ssh -vT [email protected]


On Windows, make sure all your apps agree on HOME. Msys will surprisingly NOT do it for you. I had to set an environment variable because ssh and git couldn't seem to agree on where my .ssh directory was.


I was getting this error because I generated the ssh keys with the wrong email. I was able to connect using ssh, but not using git. The solution was to regenerate the keys using the main email address of my github account.


I was able to get over this issue by following below steps in my ubuntu system. As i was experimenting with passwordless ssh to the system.

sudo vi /etc/ssh/sshd_config

1) Commented below : #Change to no to disable tunnelled clear text passwords #PasswordAuthentication yes PasswordAuthentication no ----> commented this.

2) Then restarted the sshd daemon as below.

service sshd restart


For me the problem was using sudo:

sudo git clone [email protected]:userName/repo.git was resulting in the error mentioned above.

So to fix this I chown the folder I was trying to clone into

sudo chown -R $USER:$USER /var/www/iqge.org/html

then using this git clone [email protected]:userName/repo.git was successfully done


First of all, I recommend checking some standard things like:

  • login as the correct user in your system,
  • have the right private key in the right location in your system,
  • try to connect with the correct username, hostname, and port,
  • have the public key in the right location (and for the right user) in the external server,
  • restarted the ssh service at your computer:
service ssh restart

(or in another way depending on how you manage services in your system...)

It was enough for me.


Let me share my experience too,

I was trying to clone some project from the Gerrit repo where I got my public keys in account settings.

On the first attempt to make git clone I got the following error:

Unable to negotiate with XX.XX.XX.XX port XXX: no matching key exchange
method found. Their offer: diffie-hellman-group1-sha1

I figured out that I need to pass the SSH option -oKexAlgorithms=+diffie-hellman-group1-sha1 somehow to git clone.

Hopefully GIT_SSH_COMMAND environment variable did the job:

export GIT_SSH_COMMAND="ssh -oKexAlgorithms=+diffie-hellman-group1-sha1"

But git clone still didn't start to work.. Now it throws the (on topic):

Permission denied (publickey).

I got already SSH keys and didn't want to regenerate them. I checked plain SSH connection to the host and it was ok:

****    Welcome to Gerrit Code Review    ****

  Hi XXXXX, you have successfully connected over SSH.

  Unfortunately, interactive shells are disabled.
  To clone a hosted Git repository, use:

  git clone ssh://[email protected]:xxx/REPOSITORY_NAME.git

I was confused a bit. I started again and turned on the debug for SSH via -vvv option. And I saw the following:

debug1: read_passphrase: can't open /dev/tty: No such device or address

Possibly, it was an overhead for the GIT_SSH_COMMAND env variable - my key was secured with passphrase (and I entered it when I was checking the login to the git repo host).

So, I decided to get rid of the phasphrase then. A simple command helped me:

ssh-keygen -p

Then I entered my passphrase for the "old passphrase" and just hit ENTER twice on the "new passphare" to leave it empty i.e. with no passphrase at all and to confirm my choice.

After that I got the freshly cloned repo on my local disk.


One of the easiest way

go to terminal-

  git push <Git Remote path> --all

I also had the exact same error.

The problem was that when copying the public key into BitBucket (in my case), a non-visible newline at the end was copy/pasted.

So when copying the public key, first copy it to notepad, remove the empty line at the end, copy it, and paste it.


In my case, I have reinstalled ubuntu and the user name is changed from previous. In this case the the generated ssh key also differs from the previous one.

The issue solved by just copy the current ssh public key, in the repository. The key will be available in your user's /home/.ssh/id_rsa.pub


Execute the terminal as admin.

If the terminal can't see your .ssh it will return that error.


I had to copy my ssh keys to the root folder. Google Cloud Compute Engine running Ubuntu 18.04

sudo cp ~/.ssh/* /root/.ssh/

Another possibility on Windows, which is not covered in any of these answers, and is not covered in the git or github docs on troubleshooting:

git may be using a different openssh executable than you think it is.

I was receiving the Permission denied (public key) error when trying to clone or pull from github and ssh.dev.azure.com, and I'd followed all the instructions and verified that my SSH keys were setup correctly (from SSH's standpoint) using ssh -vT [email protected] and ssh -vT [email protected]. And was still getting these errors:

[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

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

I eventually figured out that the problem is that Git for Windows, and Windows, both have their own versions of openssh. This is documented here: https://github.com/desktop/desktop/issues/5641

I was relying on the Windows ssh-agent service to store my ssh key passphrases, so git (with it's separate version of openssh) couldn't read my private keys. I consider it a bug that this error message is used - it's misleading.

The fix was:

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"

Or in your ~/.gitconfig:

[core]
    sshCommand = 'C:\\Windows\\System32\\OpenSSH\\ssh.exe'

Perhaps this will be fixed in git for Windows soon, but this is the 2nd time I've wasted time on this issue.


I have just experienced this issue while setting my current project, and none of the above solution works. so i tried looking what's really happening on the debug list using the command ssh -vT [email protected]. I notice that my private key filename is not on the list. so renaming the private key filename to 'id_rsa' do the job. hope this could help.


I was struggling with same problem that's what i did and i was able clone the repo. I followed these procedure for iMac.

First Step : Checking if we already have the public SSH key.

  1. Open Terminal.
  2. Enter ls -al ~/.ssh to see if existing SSH keys are present:

Check the directory listing to see if you already have a public SSH key.Default public are one of the following d_dsa.pub,id_ecdsa.pub,id_ed25519.pub,id_rsa.pub

If you don't find then go to step 2 otherwise follow step 3

Step 2 : Generating public SSH key

  1. Open Terminal.
  2. Enter followong command with you valid email address that you use for github ssh-keygen -t rsa -b 4096 -C "[email protected]"
  3. You will see following in terminal Generating public/private rsa key pair. When it prompts to"Enter a file in which to save the key," press Enter. This accepts the default file location. When it prompts to Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter] Just press enter again. At the prompt, type a secure passphrase.
  4. Enter passphrase (empty for no passphrase): [Type a passphrase] press enter if you don't want to Enter same passphrase again: [Type passphrase again] press enter again

This will generate id_rsa.pub

Step 3: Adding your SSH key to the ssh-agent

  1. Interminal type eval "$(ssh-agent -s)"
  2. Add your SSH key to the ssh-agent. If you are using an existing SSH key rather than generating a new SSH key, you'll need to replace id_rsa in the command with the name of your existing private key file. Enter this command $ ssh-add -K ~/.ssh/id_rsa

Now copy the SSH key and also add it to you github account

  1. In terminal enter this command with your ssh file name pbcopy < ~/.ssh/id_rsa.pub This will copy the file to your clipboard Now open you github account Go to Settings > SSH and GPG keys > New SSH key Enter title and paste the key from clipboard and save it. Voila you're done.

It worked for me

ssh -i [your id_rsa path] -T [email protected]

I hit this error because I needed to give my present working directory permissions 700:

chmod -R 700 /home/ec2-user/

The easiest solution to this, when you are trying to push to a repository with a different username is:

 git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

I met the same issue because of I was thought the difference between SSH and HTTPS is

https://github.com/USERNAME/REPOSITORY.git

ssh://github.com/USERNAME/REPOSITORY.git

So I changed from HTTPS to SSH just by changing https:// to ssh:// nothing on the end of the url was changed.

But the truth is:

https://github.com/USERNAME/REPOSITORY.git

[email protected]:USERNAME/REPOSITORY.git

Which means I changed ssh://github.com/USERNAME/REPOSITORY.git to [email protected]:USERNAME/REPOSITORY.git it works.

Stupid error but hope helps someone!


The github help link helped me sort out this problem. Looks like the ssh key was not added to the ssh-agent. This is what I ended up doing.

Command 1:

Ensure ssh-agent is enabled. The command starts the ssh-agent in the background:

eval "$(ssh-agent -s)"

Command 2:

Add your SSH key to the ssh-agent:

ssh-add ~/.ssh/id_rsa

These are the steps I followed in windows 10

  1. Open Git Bash.

  2. Generate Public Key:

    ssh-keygen -t rsa -b 4096 -C "[email protected]"
    
  3. Copy generated key to the clipboard (works like CTRL+C)

    clip < ~/.ssh/id_rsa.pub
    
  4. Browser, go to Github => Profile=> Settings => SSH and GPG keys => Add Key

  5. Provide the key name and paste clipboard (CTRL+V).

  6. Finally, test your connection (Git bash)

    ssh -T [email protected]
    

Thanks!


Steps for Mac:

  1. Switch user ( sudo su - jenkins)
  2. Generate key ( ssh-keygen -t rsa -b 4096 -C "username") . Username is one with which you are using with jenkins.
  3. Copy generated public key (cat ~/.ssh/id_rsa.pub).
  4. Paste the key to git account. (Settings -> SSH and CPG keys -> New ssh keys -> Enter name of the key (can be any) and paste the key to description).

Possible that public/private config is incorrect. please follow the steps to do it. execute command anywhere in window

ssh-keygen -o -f ~/.ssh/id_rsa

now go to the c://users/xyz/.ssh/ and open the id_rsa key (path can vary) now go to the gitlab and userprofile> setting>ssh keys and add your key here. now try clone


Got same error report.

Fixed with using HTTP instead. Since I don't want set "SSH keys" for a test PC.

Change URL to HTTP when clone:

git clone https://github.com/USERNAME/REPOSITORY.git

My problem is a little bit different: I have URL set when adding a existing local repo to remote, by using:

git remote add origin ssh://github.com/USERNAME/REPOSITORY.git

To fix it, reset URL to HTTP:

git remote set-url origin https://github.com/USERNAME/REPOSITORY.git

BTW, you may check your URL using command:

git remote -v
origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
origin  https://github.com/USERNAME/REPOSITORY.git (push)

Hope this will help some one like me. :D


I was getting the same error. My problem was mixing in sudo.

I couldn't create the directory I was cloning into automatically without prefixing the git clone command with sudo. When I did that, however, my ssh keys where not being properly referenced.

To fix it, I set permissions via chmod on the parent directory I wanted to contain my clone so I could write to it. Then I ran git clone WITHOUT a sudo prefix. It then worked! I changed the permissions back after that. Done.


Visual guide (Windows)

1 of 2. Git batch side

1.1. Open git batch (Download her) enter image description here

1.2. Paste the text below (Change to your GitHub account email)

$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

enter image description here

1.3. Press Enter (Accepts the default file location) enter image description here

1.4. Click Enter Twice (Or set SSH key passphrases - Gitbub passphrases docs)

> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]

1.5. The key generate:

Your identification has been saved in /c/Users/user/.ssh/id_rsa...

1.6. Copy the SSH key to your clipboard.

$ clip < ~/.ssh/id_rsa.pub

2 of 2. Github website user side

Under user setting enter image description here

SSH and GPG keys => New SSH key: enter image description here

Paste the code from step 1.6 enter image description here

Done :)

enter image description here


If someone doesn't want to use SSH use HTTPS :

enter image description here

Github docs: https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh


In addition to Rufinus' reply, the shortcut to copy your ssh key to the clipboard in Windows is:

  • type id_rsa.pub | clip

Refs:


In MAC, go to Terminal

1) Navigate to Home Directory using command - cd ~

2) cd .ssh && ssh-keygen (For Defaults, click on Enter/Return key for both inputs)

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa):      
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/usernmae/.ssh/id_rsa.

3) After that , Do "ls". you will find id_rsa.pub file.

4) Copy the contents in the id_rsa.pub file (read using the cat command - cat id_rsa.pub)

5) Navigate to BitBucket or any version tool which supports the SSH keys. Paste the contents using the Add Key Option

That's it. Try to commit and push now.

enter image description here


Are you in a corporate environment? Is it possible that your system variables have recently changed? Per this SO answer, ssh keys live at %HOMEDRIVE%%HOMEPATH%\.ssh\id_rsa.pub. So if %HOMEDRIVE% recently changed, git doesn't know where to look for your key, and thus all of the authentication stuff.

Try running ssh -vT [email protected]. Take note of where the identity file is located. For me, that was pointing not to my normal \Users\MyLogin but rather to a network drive, because of a change to environment variables pushed at the network level.

The solution? Since my new %HOMEDRIVE% has the same permissions as my local files, I just moved my .ssh folder there, and called it a day.


$ cd ~
$ cd .ssh
$ chmod 400 id_rsa

This error can happen when you are accessing the SSH URL (Read/Write) instead of Git Read-Only URL but you have no write access to that repo.

Sometimes you just want to clone your own repo, e.g. deploy to a server. In this case you actually only need READ-ONLY access. But since that's your own repo, GitHub may display SSH URL if that's your preference. In this situation, if your remote host's public key is not in your GitHub SSH Keys, your access will be denied, which is expected to happen.

An equivalent case is when you try cloning someone else's repo to which you have no write access with SSH URL.

In a word, if your intent is to clone-only a repo, use HTTPS URL (https://github.com/{user_name}/{project_name}.git) instead of SSH URL ([email protected]:{user_name}/{project_name}.git), which avoids (unnecessary) public key validation.


Update: GitHub is displaying HTTPS as the default protocol now and this move can probably reduce possible misuse of SSH URLs.


Guys this is how it worked for me:

  1. Open terminal and go to user [See attached image]
  2. Open .ssh folder and make sure it doesn't have any file like id_rsa or id_rsa.pub otherwise sometimes it wont properly rewrite files
  3. git --version [Check for git installation and version]
  4. git config --global user.email "your email id"
  5. git config --global user.name "your name"
  6. git config --list [make sure you have set your name & email]
  7. cd ~/.ssh
  8. ssh-keygen, it prompts for saving file, allow it
  9. cat ~/.ssh/id_rsa.pub [Access your public key & copy the key to gerrit settings]

Note: You should not be using the sudo command with Git. If you have a very good reason you must use sudo, then ensure you are using it with every command (it's probably just better to use su to get a shell as root at that point). If you generate SSH keys without sudo and then try to use a command like sudo git push, you won't be using the same keys that you generated

enter image description here

enter image description here


I was getting a similar Permission denied (publickey) error when trying to run a makefile.

As an alternative to the SSH steps above, you can Install the native GitHub for Mac application.

Click Download GitHub for Mac from - https://help.github.com/articles/set-up-git#platform-mac

Once you complete setup with your git hub account (I also installed the git hub command line tools but unsure if this step is required or not) then I received an email -

[GitHub] A new public key was added to your account

and my error was fixed.


Its pretty straight forward. Type the below command

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Generate the SSH key. Open the file and copy the contents. Go to GitHub setting page , and click on SSH key . Click on Add new SSH key, and paste the contents here. That's it :) You shouldn't see the issue again.


More extensive troubleshooting and even automated fixing can be done with:

ssh -vT [email protected]

Source: https://help.github.com/articles/error-permission-denied-publickey/


If you have more than one key you may need to do ssh-add private-keyfile


Note that (at least for some projects) you must have a github account with an ssh key.

Look at the keys listed in your authentication agent (ssh-add -l)
(if you don't see any, add one of your existing keys with ssh-add /path/to/your/key (eg: ssh-add ~/.ssh/id_rsa))
(if you don't have any keys, first create one. See: http://rcsg-gsir.imsb-dsgi.nrc-cnrc.gc.ca/documents/internet/node31.html or just google ssh-keygen)

To verify that you have a key associated with your github account:

Go to: https://github.com/settings/ssh

You should see at least one key with a hash key matching one of the hashes you saw when you typed ssh-add -l just a minute ago.

If you don't, add one, then try again.


This strange error, in my case was a symptom of gnome-keyring-daemon incorrectly naming the key to which it required a password.

I follow the steps outlined here, and entered the password via the terminal. The error, aka the confounding GUI interface, was resolved. See: https://askubuntu.com/questions/3045/how-to-disable-gnome-keyring


When ever I get a new computer at work or switch jobs these are steps I follow setup github access. Mac or Windows

-Go to https://github.[yourWorkDomain].com. navigate to Settings ? Developer Settings ? Personal access tokens
-Generate a new token
-Set the token description and only check the “repo” box for scope (this will give you repo:status, repo_deployment, public_repo, repo:invite access)

-After your are given the token, copy it (don't navigate away yet, confirm the next two steps work)
-Try to clone the repo again(using “https”)
-For the username use your Username
-For the password, paste the token you copied
-All future requests should work now without asking for your username and password.


The basic GIT instructions did not make a reference to the SSH key stuff. Following some of the links above, I found a git help page that explains, step-by-step, exactly how to do this for various operating systems (the link will detect your OS and redirect, accordingly):

http://help.github.com/set-up-git-redirect/

It walks through everything needed for GITHub and also gives detailed explanations such as "why add a passphrase when creating an RSA key." I figured I'd post it, in case it helps someone else...


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to ssh

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058" How to solve "sign_and_send_pubkey: signing failed: agent refused operation"? key_load_public: invalid format ssh connection refused on Raspberry Pi Getting permission denied (public key) on gitlab Verify host key with pysftp Can't connect to Postgresql on port 5432 Checkout Jenkins Pipeline Git SCM with credentials? How to open remote files in sublime text 3 how to setup ssh keys for jenkins to publish via ssh

Examples related to ssh-keys

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"? Windows 10 SSH keys How can I remove an SSH key? ssh-copy-id no identities found error SSH Key - Still asking for password and passphrase Using SSH keys inside docker container Failed to add the host to the list of know hosts Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly Push to GitHub without a password using ssh-key how to generate public key from windows command prompt

Examples related to public-key

key_load_public: invalid format Verify host key with pysftp Github permission denied: ssh add agent has no identities git push: permission denied (public key) Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes Using scp to copy a file to Amazon EC2 instance? How to ssh connect through python Paramiko with ppk public key Adding a public key to ~/.ssh/authorized_keys does not log me in automatically Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly