Windows SSH 免密码登录 Ubuntu 快速指南
1. Windows 生成密钥(PowerShell)
powershell
ssh-keygen -t ed25519 -f $env:USERPROFILE\.ssh\id_ed25519
# 提示输入口令时直接回车两次(留空)
2. 上传公钥到 Ubuntu(一次输入密码)
powershell
type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh user@host "mkdir -p ~/.ssh && umask 077 && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys"
将 user@host 替换为实际用户名和主机 IP。
3. Ubuntu 端修复权限(重要)
bash
# 取消 home 目录对组/其他的写权限
chmod go-w ~
chmod 750 ~
# 确保 .ssh 和 authorized_keys 权限正确
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
# 确保属主正确
sudo chown -R $(whoami):$(whoami) ~/.ssh
4. 测试登录(Windows)
powershell
ssh user@host
# 应该不再要求密码
常见问题排查
| 问题 | 解决方案 |
|---|---|
| 仍要求密码 | 检查 home/~/.ssh 权限;运行 chmod go-w ~ 和 chmod 700 ~/.ssh |
| 公钥格式错误 | 修复 CRLF:dos2unix ~/.ssh/authorized_keys |
| sshd 不允许公钥 | 确保 /etc/ssh/sshd_config 有 PubkeyAuthentication yes |
| 权限被拒绝 | 运行 chown -R $(whoami):$(whoami) ~/.ssh |
调试(如需详细信息)
Windows 客户端查看详细输出:
powershell
ssh -vvv user@host
Ubuntu 服务器查看登录日志:
bash
sudo tail -n 50 /var/log/auth.log
可选:禁用密码登录(确认公钥工作后)
bash
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl reload ssh