I'm writing a shell script where I need to obtain an IdentityFile
from an ssh config file. The ssh config file looks like this:
Host AAAA
User aaaa
IdentityFile /home/aaaa/.ssh/aaaaFILE
IdentitiesOnly yes
PubkeyAuthentication=yes
PreferredAuthentications=publickey
Host BBBB
User bbbb
IdentityFile /home/aaaa/.ssh/bbbbFILE
IdentitiesOnly yes
PubkeyAuthentication=yes
PreferredAuthentications=publickey
Host CCCC
User cccc
IdentityFile /home/aaaa/.ssh/ccccFILE
IdentitiesOnly yes
PubkeyAuthentication=yes
PreferredAuthentications=publickey
I want to obtain the string following IdentityFile
based on a given Hostname
and put it in a variable. The hostname will be provided by a shell variable called ${HOSTNAME}
.
I was able to use the answer at Bash extract user for a particular host from ssh config file to read the config file and grep for a single specific IdentityFile
based on a single specific Hostname
, but I can't get the hang of passing a variable into awk.
So far I've tried
SSH_CONFIG="/home/aaaa/.ssh/config"
# Note AAAA is the hostname for this case
KEY=$(awk '/^Host AAAA$/{x=1}x&&/IdentityFile/{print $2;exit}' ${SSH_CONFIG})
echo "${KEY}"
OUTPUT: "/home/aaaa/.ssh/aaaaFILE"
which works because I'm giving the exact hostname to parse. But using
SSH_CONFIG="/home/aaaa/.ssh/config"
HOSTNAME=AAAA
KEY=$(awk -vcon="${HOSTNAME}" '/^Host con$/{x=1}x&&/IdentityFile/{print $2;exit}' ${SSH_CONFIG})
echo "${KEY}"
OUTPUT: ""
does not work. I know for a fact ${HOSTNAME}
is being set because I am setting myself (and echoing it). I would like to pass a variable because I do not want the hostname hardcoded and will not know what the value is until the script is called.
I am also stuck using and older version of ssh (OpenSSH_6.6.1) which does not have the convenient ssh -G HOSTNAME
option.
What am I missing when it comes to awk variables? Is there a better way to do this?
grep
allows for more brevity. – Indocile