Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab an IdentityFile from an ssh config based on a variable hostname via shell script

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?

like image 461
Wimateeka Avatar asked Aug 14 '17 20:08

Wimateeka


1 Answers

I appreciate the scripting attempts, but OpenSSH client already knows how to parse the configuration:

ssh -G $hosname | grep identityfile | awk '{print $2}' | head -n 1

note, that it will also list the default identities, but with IdentitiesOnly=yes it should list the one from configuration as the first one.

like image 191
Jakuje Avatar answered Oct 04 '22 02:10

Jakuje