I want to create a Linux shell (bash-) script which creates an SSH tunnel, runs a local command which uses that tunnel and finally closes the tunnel and the surrounding SSH connection.
To make this less difficult to explain consider there is a local SSH configuration to a host called 'remoteserver' containing a local private key without a password, so
ssh remoteserver -L 4444:targetserver:5555
localclient --port 4444
sudo killall ssh
You can try something like
TIMEOUT=60 # seconds ssh remoteserver -L 4444:targetserver:5555 sleep $TIMEOUT & localclient --port 4444
The tunnel will close itself automatically after $TIMEOUT seconds. Note that using the
& is only valid with passwordless connections. Otherwise you need to use the
-f flag of SSH.
ssh -N remoteserver -L 4444:targetserver:5555 & sshpid=$! localclient --port 4444 kill $sshpid
will kill the tunnel just after
localclient executes. Note that this will not work with the
-f flag because the process double forks.