You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何命令行SSH可正常连接,但~/.ssh/config配置不生效?

SSH配置连接失败问题排查与解决

问题场景

  • 客户端xps.local上,直接执行命令ssh bob@blueberry.local -i ~/.ssh/blueberry_rsa可成功连接服务器blueberry.local
  • 通过~/.ssh/config配置文件连接时,执行ssh bob@blueberry.local提示bob@blueberry.local: Permission denied (publickey)公钥认证错误
  • 已尝试移除部分配置项无效,另有一台配置类似的客户端可正常连接

相关配置

服务器blueberry.local的sshd配置(/etc/ssh/sshd_config)

UsePAM yes
Banner none
AddressFamily any
Port 22
X11Forwarding no
PermitRootLogin no
GatewayPorts no
PasswordAuthentication no
KbdInteractiveAuthentication no
PrintMotd no
AuthorizedKeysFile %h/.ssh/authorized_keys %h/.ssh/authorized_keys2 /etc/ssh/authorized_keys.d/%u
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ed25519_key


KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com

LogLevel INFO
UseDNS no

客户端xps.local的~/.ssh/config配置

Host blueberry.stark.local
  Port 22
  HostName blueberry.local
  IdentityFile ~/.ssh/blueberry_rsa
  IdentitiesOnly yes

问题原因

客户端~/.ssh/config中配置的Host字段为blueberry.stark.local,而实际执行的连接命令是ssh bob@blueberry.local——SSH会根据命令中的主机名匹配配置文件里的Host项,两者不匹配时,SSH不会使用该配置块中的IdentityFile等参数,而是尝试使用默认私钥(如id_rsa、id_ed25519等),这些默认私钥未被服务器授权,因此触发公钥认证失败。

另一台客户端能正常使用,大概率是其配置文件中的Host字段与执行命令的主机名一致,或者执行的是匹配blueberry.stark.local的连接命令。

解决方法

有两种可行方案:

  1. 修改配置文件的Host字段
    将客户端~/.ssh/config中的Host项改为blueberry.local,修改后配置如下:

    Host blueberry.local
      Port 22
      HostName blueberry.local
      IdentityFile ~/.ssh/blueberry_rsa
      IdentitiesOnly yes
      User bob  # 可选,添加后可直接执行`ssh blueberry.local`无需输入用户名
    

    保存后执行ssh bob@blueberry.local即可匹配配置,使用指定私钥完成认证。

  2. 使用配置对应的主机别名连接
    保持现有配置不变,执行命令ssh bob@blueberry.stark.local,SSH会匹配到Host blueberry.stark.local的配置块,自动使用指定的私钥和主机名进行连接。


内容的提问来源于stack exchange,提问作者Nate-Wilkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:45:38