Ubuntu与CentOS 7环境下SSH密钥登录失败问题求助
Alright, you’ve gone through the initial steps for setting up SSH key auth but still hitting a wall—let’s break down the most common misconfigurations and fixes tailored to CentOS 7.
1. Critical sshd_config Settings You Must Verify
First, let’s make sure your SSH daemon is configured to allow key-based authentication. Open the config file with:
sudo nano /etc/ssh/sshd_config
Double-check these lines (uncomment them if they’re commented out, and set the values exactly):
PubkeyAuthentication yes– Enables public key loginAuthorizedKeysFile .ssh/authorized_keys– Confirms SSH knows where to look for authorized keys (this is default, but worth verifying)PasswordAuthentication no(optional, but recommended once keys work to disable password login)ChallengeResponseAuthentication no– Blocks other challenge-based auth that might interfere
After making changes, restart the SSH service to apply them:
sudo systemctl restart sshd
2. Fix Permissions for authorized_keys
You set the .ssh directory to 700 (great start!), but the authorized_keys file itself also needs strict permissions—SSH will reject keys if this file is too open. Run these commands:
chmod 600 ~/.ssh/authorized_keys chown your_username:your_username ~/.ssh/authorized_keys
Replace your_username with your actual user account name. This ensures only you can read/write the file.
3. Check SELinux Contexts (CentOS 7 Specific!)
CentOS 7 has SELinux enabled by default, and it can block SSH key access if file contexts are wrong. Run this command to restore the correct SELinux context for your .ssh directory and files:
restorecon -Rv ~/.ssh
This fixes any mislabeled files that might be preventing SSH from reading your authorized keys.
4. Test with Verbose Output to Diagnose
If you still can’t log in, run the SSH command with verbose mode to see exactly where it’s failing:
ssh -v your_username@your_server_ip
Look for lines like debug1: Authentications that can continue:—if publickey isn’t listed, the server isn’t accepting key auth. If it tries the key but says Permission denied, circle back to check permissions or SELinux.
5. Double-Check Your Public Key
Make sure you copied the entire content of id_rsa.pub into authorized_keys—no extra spaces, line breaks, or missing characters. You can also use this command to append the key directly (avoids copy-paste errors):
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Give these steps a try, and if you hit any specific errors from the verbose output, I can help narrow it down further!
内容的提问来源于stack exchange,提问作者Pathros

