这可能是一种非常不寻常的情况,但我想指定在本地计算机上执行shell(git)命令时要使用的私有SSH密钥。
基本上是这样的:
git clone git@github.com:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"
或者更好(用Ruby):
with_key("/home/christoffer/ssh_keys/theuser") do
sh("git clone git@github.com:TheUser/TheProject.git")
end
我见过使用Net::SSH连接到远程服务器的示例,该服务器使用指定的私钥,但这是一个本地命令。有可能吗?
如果你像我一样,你可以:
整理好ssh密钥保持gitclone命令简单为任意数量的存储库处理任意数量的密钥。减少ssh密钥维护。
我将密钥保存在~/.ssh/keys目录中。
我更喜欢约定而不是配置。
我认为守则就是法律;越简单越好。
步骤1-创建别名
将此别名添加到shell:alias git clone='git_SSH=SSH_wrapper git clone'
第2步-创建脚本
将此ssh_wrapper脚本添加到PATH中:
#!/bin/bash
# Filename: ssh_wrapper
if [ -z ${SSH_KEY} ]; then
SSH_KEY='github.com/l3x' # <= Default key
fi
SSH_KEY="~/.ssh/keys/${SSH_KEY}/id_rsa"
ssh -i "${SSH_KEY}" "$@"
示例
使用github.com/l3x密钥:
KEY=github.com/l3x git-clone https://github.com/l3x/learn-fp-go
以下示例还使用github.com/l3x密钥(默认情况下):
git-clone https://github.com/l3x/learn-fp-go
使用bitbucket.org/lsheehan密钥:
KEY=bitbucket.org/lsheehan git-clone git@bitbucket.org:dave_andersen/exchange.git
笔记
将SSH_wrapper脚本中的默认SSH_KEY更改为大多数时间使用的SSH_KEY。这样,您不需要在大多数时间使用KEY变量。
你可能会想,“嘿!别名、脚本和一些密钥目录都是如此,”但对我来说,这是惯例。我几乎所有的工作站(以及服务器)都是类似的配置。
我的目标是简化我定期执行的命令。
我的约定,例如Bash脚本、别名等,创建了一个一致的环境,并帮助我保持简单。
KISS和名字很重要。
有关更多设计技巧,请参阅我的书《Go》中的第4章固体设计:https://www.amazon.com/Learning-Functional-Programming-Lex-Sheehan-ebook/dp/B0725B8MYW
希望这有帮助。-莱克斯
其中许多解决方案看起来很诱人。然而,我发现以下链接中的通用git包装脚本方法最有用:
如何使用git命令指定ssh密钥文件
问题是没有git命令,例如:
git -i ~/.ssh/thatuserkey.pem clone thatuser@myserver.com:/git/repo.git
Alvin的解决方案是使用一个定义良好的bash包装器脚本来填补这一空白:
git.sh -i ~/.ssh/thatuserkey.pem clone thatuser@myserver.com:/git/repo.git
其中git.sh为:
#!/bin/bash
# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad
# https://alvinabad.wordpress.com/2013/03/23/how-to-specify-an-ssh-key-file-with-the-git-command
if [ $# -eq 0 ]; then
echo "Git wrapper script that can specify an ssh-key file
Usage:
git.sh -i ssh-key-file git-command
"
exit 1
fi
# remove temporary file on exit
trap 'rm -f /tmp/.git_ssh.$$' 0
if [ "$1" = "-i" ]; then
SSH_KEY=$2; shift; shift
echo "ssh -i $SSH_KEY \$@" > /tmp/.git_ssh.$$
chmod +x /tmp/.git_ssh.$$
export GIT_SSH=/tmp/.git_ssh.$$
fi
# in case the git command is repeated
[ "$1" = "git" ] && shift
# Run the git command
git "$@"
我可以验证这是否解决了我在使用git远程更新、git pull和git克隆进行远程比特桶回购时遇到的用户/密钥识别问题;所有这些现在都可以在cron作业脚本中正常工作,否则在有限的shell中导航会遇到困难。我还能够从R中调用这个脚本,并且仍然可以解决完全相同的cron执行问题(例如系统(“bash-git.sh-i~/.ssh/thatuserkey.pem pull”)。
并不是说R和Ruby一样,但如果R能做到这一点…O:-)