Git SSH Host Key Verification Failed 问题排查与解决

Git SSH Host Key Verification Failed 问题排查与解决

问题描述

在 VSCode 或命令行中使用 SSH 方式操作 Git 远程仓库时,遇到如下报错:

复制代码
> git fetch testgit1
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

原因分析

SSH 在首次连接一台主机时,会要求确认该主机的身份,并将主机密钥(host key)保存到 ~/.ssh/known_hosts 文件中。如果该文件中没有目标主机的密钥记录,且当前环境无法进行交互式确认(例如 VSCode 后台执行的 Git 操作),SSH 会直接拒绝连接,报出 Host key verification failed 错误。

常见触发场景:

  • 新装的系统或新创建的 SSH 环境,从未连接过该 Git 平台
  • 首次使用 SSH 协议操作 Gitee/GitHub/GitLab 等平台
  • VSCode 等 IDE 后台自动执行 git fetch,无法弹出交互式确认提示

解决方法

方法一:ssh-keyscan 自动添加(推荐)

一条命令将目标平台的主机密钥加入信任列表:

bash 复制代码
ssh-keyscan -t rsa,ecdsa,ed25519 gitee.com >> ~/.ssh/known_hosts

对其他平台同理,替换域名即可:

bash 复制代码
# GitHub
ssh-keyscan -t rsa,ecdsa,ed25519 github.com >> ~/.ssh/known_hosts

# GitLab
ssh-keyscan -t rsa,ecdsa,ed25519 gitlab.com >> ~/.ssh/known_hosts

方法二:手动测试连接触发确认

bash 复制代码
ssh -T git@gitee.com

首次连接时会提示:

复制代码
The authenticity of host 'gitee.com (xxx.xxx.xxx.xxx)' can't be established.
ECDSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

输入 yes 回车即可。成功后会自动将密钥写入 known_hosts。之后再执行 Git 操作就不会提示了。

验证是否解决

bash 复制代码
ssh -T git@gitee.com

如果输出类似以下内容,说明 SSH 连接已正常:

复制代码
Hi TDon1! You've successfully authenticated, but GITEE.COM does not provide shell access.

注意 :GitHub 的输出为 Hi username! You've successfully authenticated...,GitLab 为 Welcome to GitLab, @username!,语义相同。

扩展:known_hosts 文件说明

文件路径 说明
~/.ssh/known_hosts 用户级别,所有私钥共享
Windows 路径 C:\Users\用户名\.ssh\known_hosts
/etc/ssh/ssh_known_hosts 系统级别(需管理员权限)

每行记录一条主机密钥,格式为:

复制代码
主机名 密钥类型 密钥内容

例如:

复制代码
gitee.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNo...

总结

Host key verification failed 是 SSH 无法验证远程主机身份时的安全保护机制,本质上不是 Git 的问题,而是 SSH 配置不完整导致的。通过 ssh-keyscan 或首次手动 ssh -T 连接即可解决。建议在配置好 SSH 密钥后,顺手执行一次 ssh -T 测试,避免后续操作时被阻塞。

相关推荐
考虑考虑6 小时前
nginx路由重写
运维·后端·自动化运维
Zenova EdgeOS8 小时前
Linux 内核日志 dmesg 进阶实战:从现场过滤到持久化闭环
linux·运维·服务器
郝亚军9 小时前
ec_private.pem的生成方法
linux·运维·服务器
NendoZen9 小时前
Arch Linux解决Grub无法SAVEDEFAULT问题(uki启动问题)
linux·运维·服务器
Elastic 中国社区官方博客10 小时前
Elasticsearch:安装自行管理的 Elastic Stack 集群
大数据·运维·服务器·数据库·elasticsearch·搜索引擎·全文检索
忆挽篱笙歌10 小时前
进程控制管理
linux·运维·服务器
fengkai454512 小时前
3、Kubernetes的Namespace&Contexts&Pod&YAML格式
运维·容器·kubernetes·k8s·namespace·yaml·pod
IOT那些事儿12 小时前
Git报错:Could not get HEAD hash
git·hash·head
戴西软件12 小时前
制造研发中的AI视觉与仿真:戴西工程图纸智能审图智能体、戴西3DViz_CAE AI集成与戴西3DViz_CAD AI集成
大数据·运维·人工智能·3d·自动化·制造·rpa
javaDocker13 小时前
1800 亿科技投入砸下去,多数机构平的只是服务器,不是能力
运维·服务器·人工智能·科技·研发效能·金融科技