我们一般通过修改~/.ssh/config文件的方式来实现免输入密码的git访问,这种方式网上介绍的很详细了,这里就不再说明。今天我们要说的是另一种更加灵活的方式来实现git 的ssh-key验证。
我们知道ssh命令有个-i参数来指定identity_file
-i identity_file
Selects a file from which the identity (private key) for public key authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and
~/.ssh/id_rsa for protocol version 2. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple iden‐
tities specified in configuration files). ssh will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames.
可以通过-i参数来灵活的指定ssh-key
ssh -i ~/.ssh/test.pem user@server.com
而git是使用ssh协议来进行连接的,那么它是否也有类似于ssh命令-i参数这样可以用来灵活指定identity_file的参数呢?
很遗憾,真没有!
不过不用灰心,git还是给我们留了一扇窗的。这扇窗就是GIT_SSH,我们先来看下GIT_SSH的介绍:
GIT_SSH
If this environment variable is set then git fetch and git push will use this command instead of ssh when they need to connect to a remote system. The $GIT_SSH command will be given exactly
two arguments: the username@host (or just host) from the URL and the shell command to execute on that remote system.
To pass options to the program that you want to list in GIT_SSH you will need to wrap the program and options into a shell script, then set GIT_SSH to refer to the shell script.
Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh documentation for further details.
大致的意思是,如果你设置了GIT_SSH,那么在git fetch 和 git pull 时,会使用GIT_SSH设置的脚本命令来替换默认的ssh连接。需要注意的是GIT_SSH必须设置为一个脚本(英语渣,翻译的不准请见谅)
可以写这样一个脚本,~/ssh-git.sh
#!/bin/bash
if [ -z "$PKEY" ]; then
# if PKEY is not specified, run ssh using default keyfile
ssh "$@"
else
ssh -i "$PKEY" "$@"
fi
注意用chmod +x ssh-git.sh
命令设置可执行权限
然后设置GIT_SSH
export GIT_SSH=~/ssh-git.sh
最后
PKEY=~/.ssh/test.pem git clone user@server.com:/git/repo.git
上面的方法略显繁复,我们的目标是像ssh命令一样可以用-i参数来灵活的指定identity_file
再创建一个脚本,~/git.sh
#!/bin/bash
# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad
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 "$@"
设置执行权限之后,即可像ssh一样自由的指定identity_file
~/git.sh -i ~/.ssh/test.pem clone user@server.com:/git/repo.git
参考:
https://alvinabad.wordpress.com/2013/03/23/how-to-specify-an-ssh-key-file-with-the-git-command/