使用指定 ssh 私钥访问 git 仓库

通常来说,git 仓库上的 ssh 公钥与本地某个系统账号的 ssh 私钥关联,但有时可能会由于 CI 等需要在多台机器间分发该 ssh 私钥,这时 git clone 命令就必须要支持指定 ssh 私钥进行访问。

由于 git 版本的不同而有多种实现方式。

git < 2.3

配置 GIT_SSH 环境变量指向一个自定义的脚本:

~$ cat git-ssh.sh
#!/usr/bin/env bash

ssh -o StrictHostKeyChecking=no -F /dev/null -i /path/to/private_key $*
~$ export GIT_SSH=./git-ssh.sh
~$ git clone git@src.example.com:runsisi/secrets.git

git >= 2.3

配置 GIT_SSH_COMMAND 环境变量,直接在命令行中定义

~$ export GIT_SSH_COMMAND='ssh -o StrictHostKeyChecking=no -F /dev/null -i /path/to/private_key'
~$ git clone git@src.example.com:runsisi/secrets.git

git >= 2.10

不需要设置 GIT_SSH_COMMAND 环境变量,可以直接配置 sshCommand 选项:

~$ git config core.sshCommand 'ssh -o StrictHostKeyChecking=no -F /dev/null -i /path/to/private_key'
~$ git clone git@src.example.com:runsisi/secrets.git

注意事项

ssh 的私钥的权限必须为 600400

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for './id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: ./id_rsa

参考资料

How to specify the private SSH-key to use when executing shell command on Git?

https://stackoverflow.com/questions/4565700/how-to-specify-the-private-ssh-key-to-use-when-executing-shell-command-on-git


最后修改于 2019-04-23