git 使用指定的 ssh key

Git 提供了以下两种方式来指定使用哪个 SSH Key 进行认证:

使用 Git Config 命令

使用 git config 命令来配置 Git 的全局或本地参数。在这个命令中,可以使用 core.sshCommand 参数来指定使用哪个 SSH Key 进行认证。

例如:

# 全局范围内使用 SSH Key
$ git config --global core.sshCommand "ssh -i ~/.ssh/my_private_key"

# 仅对当前仓库使用 SSH Key
$ git config core.sshCommand "ssh -i ~/.ssh/my_private_key"

上面的命令会告诉 Git,使用 ~/.ssh/my_private_key 文件作为 SSH 私钥进行认证。

使用 Git Clone 命令

在使用 git clone 命令克隆项目时,可以通过 -c--config 参数来指定使用哪个 SSH Key 进行认证。示例如下:

$ git clone -c core.sshCommand="ssh -i ~/.ssh/my_private_key" git@github.com:user/repo.git

上面的命令将会使用 -i ~/.ssh/my_private_key 指定的 SSH Key 进行认证。

git push 使用指定的ssh private key

在使用 Git 上传代码时,可以通过指定 ssh private key 来进行身份验证而非输入用户名和密码。

  1. 打开终端(命令行),并进入到 Git 本地仓库所在目录。

输入以下命令来配置 Git 使用指定的 ssh private key:

# 如果不执行该指令,ssh-add 可能会报错:Could not open a connection to your authentication agent.
eval $(ssh-agent -s)


# 其中 /path/to/private/key 替换成你的私钥文件路径。
ssh-add /path/to/private/key
  1. 确认已将 private key 加入 ssh-agent 后,在命令行中输入以下命令来测试连接:
ssh -T git@github.com
# 如果连接成功,则会显示如下信息:"Hi {your username}! You've successfully authenticated, but GitHub does not provide shell access."
  1. 执行 Git Push 操作
git push origin master

注意事项

使用 SSH Key 进行认证时,私钥文件必须设置正确的权限(一般是 0600),否则会导致认证失败。