另一种选择是编写一个小脚本,让core.sshCommand 更智能一些 - 检查当前工作目录是否配置了特定的 SSH 密钥,如果有,请使用它,否则 - 依赖标准的 SSH 密钥解析。
这是我的第一个版本:
#!/bin/bash
key="$(git config ssh.key)"
if [ -n "$key" ]; then
ssh -o IdentitiesOnly=yes -i "$key" "$@"
else
ssh "$@"
fi
然后将其设置为 global git SSH 命令:
chmod 755 ~/.local/bin/git-ssh-command
git config --global core.sshCommand ~/.local/bin/git-ssh-command
(~/.local/bin 是"place user scripts here" on SystemD operating systems 的当前标准)
设置完成后,您可以通过设置配置选项 ssh.key 来配置任何存储库以使用特定的 SSH 密钥:
git config --local ssh.key ~/.ssh/my-non-default-private-key
其他可选技巧
- 将全局
ssh.key 设置为“默认回退到非默认 SSH 密钥”或其他内容。
- 当 git 在存储库的根目录中执行
core.sshCommand 时,您的自定义 git-ssh-command 可以查看它并对目录名称进行一些启发。这可以在 else 部分中完成,因此只有在 ssh.key 中没有特定键时才会使用启发式算法。
- 您可以添加
git remote -v 检查以添加基于遥控器的启发式方法,就像在 Eike 的脚本中一样
- 如果您想查看存储库遥控器,但有多个遥控器需要不同的密钥,您可以在脚本开头添加
remote="$1:$(sed "s,.* ,,;s,',,g"<<<"$2")" 以解析正在操作的遥控器 - 并检查($remote 将看起来像git remote -v 输出中的中间列)。
更新:
这是自定义 SSH 命令的一个版本,它查看远程 URL 并执行一些启发式方法 - 在我的例子中,我有几个不同的身份和相同的公共 git 托管服务(一个用于工作,一个用于个人等)和我可以通过查看远程 URL 来选择正确的身份(检查 Gitlab 组或 Github 组织等):
#!/bin/bash
while ! [[ "$1" =~ "git@" ]]; do shift; done # git may send ssh options
if [[ "$2" =~ ^git-lfs-authenticate.* ]]; then # reconstruct url for git-lfs
remote="$1:$(awk '{print$2}'<<<"$2")"
else # reconstruct url for standard git commands
remote="$1:$(sed "s,.* ,,;s,',,g"<<<"$2")"
fi
echo "Detected $remote from $@" >&2
key="$(git config ssh.key)"
if [ -n "$key" ]; then # use specified SSH key, if set
ssh -o IdentitiesOnly=yes -i "$key" "$@"
elif [[ "$remote" == git@gitlab.com:my-company* ]]; then # use company id
ssh -o IdentitiesOnly=yes -i ~/.ssh/company-id "$@"
elif [[ "$remote" =~ git@bitbucket.org:.*other-org.* ]]; then # bitbucket has weird urls
ssh -o IdentitiesOnly=yes -i ~/.ssh/custom-org-key "$@"
else # otherwise use whatever the agent has (my personal key)
ssh "$@"
fi