How to Fix the ‘Permission denied (publickey)’ Error in Git
Encountering the ‘Permission denied (publickey)’ error in Git can be frustrating, especially when you’re trying to push or pull code to/from a remote repository. This error typically indicates an issue with your SSH key configuration. In this guide, we’ll take you through various steps to troubleshoot and resolve this error.
Check for Existing SSH Keys
First, you need to check if you already have an SSH key pair (public and private key) on your local machine. Open your terminal and type:
ls -al ~/.ssh
This command will list the files in your .ssh
directory. Look for files named id_rsa
and id_rsa.pub
or id_ed25519
and id_ed25519.pub
. If these files exist, you already have an SSH key pair.
Generate a New SSH Key Pair (if needed)
If no SSH key pair exists, you need to generate one. Use the following command to generate a new SSH key:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
or, for enhanced security, you might want to use:
ssh-keygen -t ed25519 -C "your_email@example.com"
Follow the prompts and save the key in the default location (typically ~/.ssh
). You can also add a passphrase for extra security.
Add SSH Key to the SSH Agent
After generating the SSH key pair, you need to start the SSH agent in the background and add your SSH private key to the agent. Run the following commands:
eval "$(ssh-agent -s)"ssh-add ~/.ssh/id_rsa
or
ssh-add ~/.ssh/id_ed25519
Add SSH Key to Your Git Hosting Service
Next, you have to add the SSH public key to your Git hosting service (e.g., GitHub, GitLab, Bitbucket). Use the following command to copy your SSH public key to the clipboard:
pbcopy < ~/.ssh/id_rsa.pub
or
pbcopy < ~/.ssh/id_ed25519.pub
Alternatively, you can manually open the file and copy its contents:
cat ~/.ssh/id_rsa.pub
or
cat ~/.ssh/id_ed25519.pub
Go to your Git hosting service account settings and find the SSH Keys section. Paste your SSH public key into the provided field and save it.
Test the SSH Connection
After adding the SSH key to your account, test the connection to ensure everything is set up correctly. Use the following command:
ssh -T git@github.com
If you’re using GitLab or Bitbucket, replace github.com
with gitlab.com
or bitbucket.org
accordingly. You should receive a success message indicating that the authentication was successful.
Update Remote URL
Finally, make sure your Git repository is using the correct SSH URL. Navigate to your local repository and run:
git remote set-url origin git@github.com:username/repo.git
Replace username
with your actual GitHub username and repo.git
with the name of your repository.
Conclusion
By following these steps, you should be able to resolve the ‘Permission denied (publickey)’ error in Git. The key is to ensure that your SSH keys are properly configured and added to your Git hosting service. Once everything is correctly set up, you’ll be able to push and pull code seamlessly.