Git推送至origin master遇publickey权限拒绝,如何重连GitHub?
Hey there, let's fix this git@github.com: Permission denied (publickey) headache once and for all—this is one of the most common GitHub SSH issues, and we can work through it step by step.
Step 1: Check if you already have an SSH key pair
First, let's see if you've got existing SSH keys on your machine. Run this in your terminal:
ls -al ~/.ssh
Look for files like id_ed25519 (private key) and id_ed25519.pub (public key)—Ed25519 is the modern, recommended key type. If you don't see these, or only have older RSA keys, generate a new pair with:
ssh-keygen -t ed25519 -C "your_email@example.com"
Just press Enter through all prompts (you can set a passphrase if you want extra security, but it's optional).
Step 2: Ensure the SSH agent is running and your key is added
SSH agent manages your keys in the background—let's make sure it's active and knows about your key:
- Start the agent:
eval "$(ssh-agent -s)" - Add your private key to the agent:
(If you're using an RSA key, replacessh-add ~/.ssh/id_ed25519id_ed25519withid_rsa.)
Pro tip: If you tried adding the key before and it didn't stick, runssh-add -d ~/.ssh/id_ed25519first to remove any old entries, then re-add.
Step 3: Add your public key to your GitHub account
This is the most crucial step—GitHub needs to recognize your machine's public key:
- Copy your public key to your clipboard:
Select and copy the entire output (it starts withcat ~/.ssh/id_ed25519.pubssh-ed25519and ends with your email). - Log into GitHub, go to Settings > SSH and GPG keys > New SSH key.
- Give it a descriptive title (like "My Work Laptop") and paste the copied key into the "Key" field. Click Add SSH key.
Step 4: Test the SSH connection
Let's verify everything works before trying to push again:
ssh -T git@github.com
If you see a message like Hi [YourUsername]! You've successfully authenticated, but GitHub does not provide shell access., you're good to go!
Bonus Troubleshooting Tips (if the above steps don't work)
- Check your remote repo URL: Run
git remote -v—if your origin is using HTTPS instead of SSH, switch it with:git remote set-url origin git@github.com:YourUsername/YourRepoName.git - Fix ~/.ssh/config issues: If you have a
~/.ssh/configfile, make sure your GitHub entry looks like this (adjust the key path if needed):Host github.com HostName github.com User git IdentityFile ~/.ssh/id_ed25519 - Disable VPN/Firewall temporarily: Sometimes VPNs or strict firewalls block SSH connections to GitHub—try turning them off briefly to test.
- Confirm repo permissions: Double-check that your GitHub account has push access to the repo (you're either the owner or added as a collaborator with write permissions).
内容的提问来源于stack exchange,提问作者Batuhan Dogan

