Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!

awkRDPSSH

Bash variable in an awk search pattern

I spent some time getting this working so documenting for reference.

Trying to grab an IP address from a ssh config file works fine using a static string.

$ awk '/^Host rdpclient1$/{x=1}x&&/HostName/{print $2;exit}' ~/.ssh/Prod-config
10.1.4.4

Using double quotes and a static variable or double quotes and a bash variable does not work.

$ awk "/^Host rdpclient1$/{x=1}x&&/HostName/{print $2;exit}" ~/.ssh/Prod-config
     HostName 10.1.4.4
$ awk "/^Host $host$/{x=1}x&&/HostName/{print $2;exit}" ~/.ssh/Prod-config
     HostName 10.1.4.4

Using double quotes plus a bash variable and escaping the print variable $2 works.

$ awk  "/^Host ${host}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config
10.1.4.4

And an in a little script that use ssh config settings for my RDP through a jumphost or bastion Linux server.

Host gw01
     HostName <public IP>
     User opc
     IdentityFile mysshkey
Host rdpclient1
     HostName 10.1.4.4
     ProxyJump gw01

$ cat rdesktop_jumphost.sh 
#!/bin/bash
host=$1
privateIP=$(awk  "/^Host ${host}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config)
jumphost=$(awk "/^Host ${host}$/{x=1}x&&/ProxyJump/{print \$2;exit}" ~/.ssh/Prod-config)
jumphostIP=$(awk "/^Host ${jumphost}$/{x=1}x&&/HostName/{print \$2;exit}" ~/.ssh/Prod-config)
jumpuser=$(awk "/^Host ${host}$/{x=1}x&&/User/{print \$2;exit}" ~/.ssh/Prod-config)
localRdpPort=33389

ssh -f -N -p 22 -L $localRdpPort:$privateIP:3389 -i mysshkey $jumpuser@$jumphostIP
tunnelpid=$(ps -ef | grep $localRdpPort | grep -v grep | awk '{print $2}')

rdesktop localhost:$localRdpPort

kill $tunnelpid

admin

Bio Info for Riaan