温馨提示×

Debian SSH登录失败怎么解决

小樊
36
2025-12-30 11:41:08
栏目: 智能运维

Debian SSH 登录失败排查与修复

一 快速判断与定位

  • 先看具体报错,再用分层法定位:网络 → 端口 → 服务 → 配置 → 认证。
  • 常用命令与判定要点:
    • 查看服务状态:Debian 服务名为 ssh(非 sshd),执行:sudo systemctl status ssh;若未运行:sudo systemctl start ssh && sudo systemctl enable ssh。
    • 检查监听端口:ss -tulnp | grep ‘:22’ 或 ss -tnlp | grep ssh;正常应看到 0.0.0.0:22[::]:22 在监听。
    • 连通性测试:ping ;端口探测:telnet 22 或 nc -zv 22。结果含义:Connection refused 多为端口未开/服务未起;Connection timed out 多为链路/防火墙拦截。
    • 查看服务端日志:tail -f /var/log/auth.log | grep sshd,能直接指出认证失败、算法不匹配、被关闭等根因。

二 常见场景与对应修复

  • 服务未安装或未启动

    • 安装:sudo apt update && sudo apt install openssh-server
    • 启动与自启:sudo systemctl start ssh;sudo systemctl enable ssh
    • 再次确认状态与监听端口是否正常。
  • 端口与防火墙/云安全组拦截

    • 本地防火墙放行:sudo ufw allow 22/tcp;或 sudo ufw allow ssh;或 firewalld:sudo firewall-cmd --permanent --add-service=ssh && sudo firewall-cmd --reload。
    • 云服务器安全组:在控制台入方向放行 TCP 22(或自定义端口),必要时限制来源 IP。
  • 配置不当导致被拒或协商失败

    • 编辑:sudo nano /etc/ssh/sshd_config,核对关键项:
      • Port 22(若改端口,客户端需 -p 指定)
      • PermitRootLogin yes(临时排障可开启,生产建议禁用并用普通用户+sudo)
      • PasswordAuthentication yes(使用密码登录时必须为 yes)
      • ListenAddress 0.0.0.0(按需调整监听地址)
    • 语法检查:sudo sshd -t;重启:sudo systemctl restart ssh
    • 客户端算法不匹配(如 “no matching key exchange method found”):
      • 升级客户端或显式指定算法;服务器端可临时补充兼容算法(示例):KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256;重启 ssh。
  • 密钥认证失败

    • 客户端私钥权限:chmod 600 ~/.ssh/id_rsa;公钥已通过 ssh-copy-id 上传到服务器对应用户的 ~/.ssh/authorized_keys
    • 服务器端目录与文件权限:chmod 700 ~/.ssh;chmod 600 ~/.ssh/authorized_keys;确保属主正确。
    • 客户端 Host key 变更导致 “Host key verification failed”:ssh-keygen -R 清理旧指纹后重连。
  • 主机密钥丢失或损坏

    • /etc/ssh 下 ssh_host_* 文件缺失或权限错误会导致握手失败。修复:
      • 恢复权限:chmod 600 ssh_host_*;chmod 644 *.pub
      • 若仍异常,可备份后删除 /etc/ssh/ssh_host_*,然后重建:sudo dpkg-reconfigure openssh-server,重启 ssh。

三 安全加固与后续建议

  • 安装并配置 fail2ban 防止暴力破解:sudo apt install fail2ban;在 /etc/fail2ban/jail.local 启用 [sshd] 段(如 maxretry、bantime、findtime),重启 fail2ban。
  • 生产建议:禁用 root 登录(PermitRootLogin no)、使用密钥登录(PasswordAuthentication no)、更改默认端口(Port 2222),并同步更新防火墙/安全组规则。

四 最小化诊断命令清单

  • 服务端:systemctl status ssh;ss -tnlp | grep ‘:22’;tail -f /var/log/auth.log | grep sshd;sshd -t
  • 客户端:ssh -v -p <端口> <用户@IP>;ping ;nc -zv <端口>;ssh-keygen -R
  • 防火墙/云:ufw status;firewall-cmd --list-ports;云控制台安全组入方向规则检查

0