muffel muffel - 1 month ago 7x
Linux Question

ssh tunnel for local (not remote) command execution

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

would directly open a connection to the remote server and create a tunnel from the local port 4444 to a target server. And consider the local command would be
localclient --port 4444
, how would a script look like that opens the tunnel, executes the local command and closes the tunnel after the local client application is finished?

As it should be possible to keep other parallel ongoing SSH connections, I don't want something like
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 &
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.