在 Linux 中,要确定 Git 代码库当前使用的是哪个 SSH 密钥以及它的地址(路径),可以通过以下几个步骤来排查和确认。
🔍 原理说明
Git 本身不直接存储 SSH 密钥路径,而是通过 ssh 命令与远程仓库通信。SSH 密钥的使用由 ~/.ssh/config 文件或默认的 ~/.ssh/id_rsa, ~/.ssh/id_ed25519 等文件决定。
Git 使用的 SSH 地址通常体现在远程仓库的 URL 上,例如:
git@github.com:username/repo.git
这里的 git@github.com 会去查找 SSH 配置中是否定义了 github.com 对应使用哪个私钥。
✅ 方法一:查看 Git 远程仓库的 SSH URL(确认是否使用 SSH)
git remote -v
输出示例:
origin git@github.com:your-username/your-repo.git (fetch)
origin git@github.com:your-username/your-repo.git (push)
如果是 git@... 格式,说明使用的是 SSH 协议。
主机名是 github.com(或其他如 gitlab.com、your-git-server.com)。
✅ 方法二:查看 SSH 配置文件,确定使用哪个密钥
SSH 客户端会读取 ~/.ssh/config 文件来决定连接某个主机时使用哪个私钥。
- 查看 SSH 配置文件:
cat ~/.ssh/config
或:
nano ~/.ssh/config
示例内容:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github
IdentitiesOnly yes
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_gitlab
👉 在这个例子中:
连接 github.com 时使用的是 ~/.ssh/id_rsa_github 这个私钥。
- 如果没有 ~/.ssh/config 文件
SSH 会使用默认的密钥文件,按顺序尝试:
~/.ssh/id_rsa
~/.ssh/id_dsa
~/.ssh/id_ecdsa
~/.ssh/id_ed25519
所以,Git 会默认使用 ~/.ssh/id_rsa(如果存在)。
你可以检查这些文件是否存在:
ls -al ~/.ssh/
输出中类似:
-rw------- 1 user user 1675 Apr 10 10:00 id_rsa_github
-rw-r--r-- 1 user user 414 Apr 10 10:00 id_rsa_github.pub
👉 私钥文件(无 .pub 后缀)就是正在使用的密钥(如果没有配置 ~/.ssh/config,则优先使用 id_rsa 或 id_ed25519)。
✅ 方法三:使用 SSH 调试模式查看实际使用的密钥
你可以通过以下命令模拟 Git 使用的 SSH 连接,查看实际加载了哪个密钥:
ssh -vT git@github.com
⚠️ 将 github.com 替换为你实际使用的 Git 服务器(如 gitlab.com、gitee.com、自建 Git 服务器等)
在输出中查找类似:
debug1: identity file /home/youruser/.ssh/id_rsa_github type 0
debug1: Offering public key: /home/youruser/.ssh/id_rsa_github RSA SHA256:...
debug1: Authentication succeeded (publickey).
✅ 这说明实际使用的是 /home/youruser/.ssh/id_rsa_github 这个私钥。
✅ 方法四:查看 SSH 代理(ssh-agent)中加载的密钥
如果你使用了 ssh-agent,可以通过以下命令查看已加载的密钥:
ssh-add -l
输出示例:
2048 SHA256:abcdef... /home/user/.ssh/id_rsa_github (RSA)
这表示 id_rsa_github 已被加载到 SSH 代理中,可能会被 Git 使用。
查看具体是哪个文件:
ssh-add -L
✅ 总结:如何确定 Git 使用的 SSH 密钥?
步骤 命令 / 操作
-
确认是否使用 SSH git remote -v(看是否是 git@…)
-
查看 SSH 配置 cat ~/.ssh/config(找 IdentityFile)
-
查看默认密钥 ls -al ~/.ssh/(看 id_rsa, id_ed25519 等)
-
调试 SSH 连接 ssh -vT git@github.com(看实际加载的密钥)
-
检查 ssh-agent ssh-add -l(看代理中加载了哪些密钥)
📌 小贴士推荐为不同平台配置 ~/.ssh/config,避免混淆。
5058

被折叠的 条评论
为什么被折叠?



