git 指定 ssh 密钥

六月 17, 2026 [git] #git #ssh #配置

git clone 不能像 ssh 那样直接在命令中加 -i 指定私钥,但可以通过以下两种方式实现。

临时指定(单次命令)

在命令前加 GIT_SSH_COMMAND 环境变量:

GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_work" git clone git@github.com:user/repo.git

后续的 pushpull 等操作需要同样带上环境变量,比较适合 CI/CD 场景。

调试连接问题时加 -v

GIT_SSH_COMMAND="ssh -v -i ~/.ssh/id_rsa_work" git clone git@github.com:user/repo.git

单仓库固定配置

进入仓库目录后执行:

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_work"

此后仅该仓库的 fetchpushpull 等操作自动使用指定密钥,其他仓库不受影响。配置保存在 .git/config 中,适合长期使用某个特定密钥的仓库。

查看当前仓库的 SSH 命令配置:

git config core.sshCommand

注意事项

私钥权限必须为 600,否则 SSH 会拒绝使用:

chmod 600 ~/.ssh/id_rsa_work

确保对应公钥已添加到 Git 服务器的 SSH Keys 中。