我們一般通過修改~/.ssh/config文件的方式來實(shí)現(xiàn)免輸入密碼的git訪問篙挽,這種方式網(wǎng)上介紹的很詳細(xì)了造垛,這里就不再說明瑞凑。今天我們要說的是另一種更加靈活的方式來實(shí)現(xiàn)git 的ssh-key驗(yàn)證腕巡。
我們知道ssh命令有個-i參數(shù)來指定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參數(shù)來靈活的指定ssh-key
ssh -i ~/.ssh/test.pem user@server.com
而git是使用ssh協(xié)議來進(jìn)行連接的骚烧,那么它是否也有類似于ssh命令-i參數(shù)這樣可以用來靈活指定identity_file的參數(shù)呢顶瞒?
很遺憾夸政,真沒有!
不過不用灰心榴徐,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.
大致的意思是,如果你設(shè)置了GIT_SSH耗帕,那么在git fetch 和 git pull 時朋譬,會使用GIT_SSH設(shè)置的腳本命令來替換默認(rèn)的ssh連接。需要注意的是GIT_SSH必須設(shè)置為一個腳本(英語渣兴垦,翻譯的不準(zhǔn)請見諒)
可以寫這樣一個腳本徙赢,~/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
命令設(shè)置可執(zhí)行權(quán)限
然后設(shè)置GIT_SSH
export GIT_SSH=~/ssh-git.sh
最后
PKEY=~/.ssh/test.pem git clone user@server.com:/git/repo.git
上面的方法略顯繁復(fù),我們的目標(biāo)是像ssh命令一樣可以用-i參數(shù)來靈活的指定identity_file
再創(chuàng)建一個腳本探越,~/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 "$@"
設(shè)置執(zhí)行權(quán)限之后狡赐,即可像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/