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


i'm writing shell script need obtain identityfile ssh config file. ssh config file looks 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 obtain string following identityfile based on given hostname , put in variable. hostname provided shell variable called ${hostname}.

i able use answer @ bash extract user particular host ssh config file read config file , grep single specific identityfile based on single specific hostname, can't hang of passing variable awk.

so far i've tried

ssh_config="/home/aaaa/.ssh/config" # note aaaa hostname 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 exact hostname parse. 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. know fact ${hostname} being set because setting myself (and echoing it). pass variable because not want hostname hardcoded , not know value until script called.

i stuck using , older version of ssh (openssh_6.6.1) not have convenient ssh -g hostname option.

what missing when comes awk variables? there better way this?

with gnu grep , perl compatible regular expressions:

hostname="aaaa" grep -poz "host $hostname(.*\n)*?.*identityfile \k.*" ~aaaa/.ssh/config 

output:

 /home/aaaa/.ssh/aaaafile 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -