查看 Git 当前使用的 SSH 密钥目录

作者: adm 分类: linux 发布时间: 2025-04-18

查看 Git 当前使用的 SSH 密钥目录

方法1:查看 Git 全局/本地配置

# 查看当前项目配置
git config core.sshCommand

# 查看全局配置
git config --global core.sshCommand

如果输出类似 ssh -i /自定义路径/密钥名,说明指定了特定密钥。

方法2:查看 SSH 实际使用的密钥(调试模式)

# 在你的 Git 项目目录下执行
GIT_SSH_COMMAND="ssh -vvv" git pull 2>&1 | grep "identity file"

输出会显示 SSH 尝试了哪些密钥文件:

text
debug1: identity file /home/user/.ssh/id_rsa type 0
debug1: identity file /home/user/.ssh/id_ed25519 type -1

方法3:查看默认行为

如果上述配置都为空,Git 使用 SSH 默认行为,即读取 ~/.ssh/ 下的标准文件名:

id_rsa
id_ecdsa
id_ed25519
id_dsa

二、更改 SSH 密钥路径

方法1:通过 Git 配置指定(推荐 — 针对当前项目)

# 进入你的 Git 项目目录
cd /path/to/your/project

# 为这个项目指定特定的私钥
git config core.sshCommand "ssh -i /新路径/你的私钥文件名"

例如:

git config core.sshCommand "ssh -i /home/user/keys/codeup_rsa"

方法2:通过 Git 全局配置(所有项目)

git config --global core.sshCommand "ssh -i /新路径/你的私钥文件名"

方法3:通过 SSH config 文件(最灵活,推荐多密钥管理)

编辑或创建 ~/.ssh/config(注意:这里是 ~/.ssh/config,不是项目目录):

nano ~/.ssh/config

添加配置(按主机区分):

# 阿里云 CodeUp
Host codeup.aliyun.com
    HostName codeup.aliyun.com
    User git
    IdentityFile /新路径/你的私钥文件名
    IdentitiesOnly yes

# GitHub
Host github.com
    HostName github.com
    User git
    IdentityFile /另一个路径/github_key
    IdentitiesOnly yes

优点:

不同主机自动使用不同密钥
不需要修改 Git 配置
一个配置文件管理所有密钥
方法4:通过环境变量(临时生效)

export GIT_SSH_COMMAND="ssh -i /新路径/你的私钥文件名"
git pull

三、查看当前 Git 项目实际使用的密钥

在项目目录执行:

# 查看所有相关配置
echo "=== Git SSH 命令 ==="
git config core.sshCommand

echo -e "\n=== 全局 Git SSH 命令 ==="
git config --global core.sshCommand

echo -e "\n=== SSH config 中针对 codeup 的配置 ==="
cat ~/.ssh/config 2>/dev/null | grep -A 3 "codeup.aliyun.com"

echo -e "\n=== 实际执行的 SSH 命令 ==="
GIT_SSH_COMMAND="echo" git pull 2>&1 | head -1

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!