0

It's a continuation for question: Execution of a command locally after ssh tunneling".

I have something like this:

ssh -f -L 555:localhost:555 10.0.0.1 sleep 10
vncviewer

However, in such case ssh connection goes to background and I can't run any commands on remote machine.

So, my question is, how can I stay within an ssh console, and run vncviewer? In my case it is TigerVNC.

1 Answers1

1

If you really need to establish the tunnel first and run vncviewer later and only then get to the remote console, this is the basic script:

#!/bin/sh

tmpd="$(mktemp -d)" || exit 1         # temporary directory creation
srvr=10.0.0.1                         # remote server
sckt="$tmpd"/"$$-${srvr}".socket      # control socket for SSH connection sharing

clean() { rm -rf "$tmpd"; }           # cleaning function, removes the temporary directory

                                      # establishing SSH master connection
ssh -o ControlMaster=yes \
    -o ControlPath="$sckt" \
    -o ExitOnForwardFailure=yes \
    -Nf -L 555:localhost:555 "$srvr" || { clean; exit 2; }

                                      # the tunnel is now established
vncviewer >/dev/null 2>&1 &           # silent custom command in the background
ssh -o ControlPath="$sckt" "$srvr"    # reusing the master connection
                                      # (exit the remote shell to continue)
wait $!                               # waiting for vncviewer to terminate
ssh -o ControlPath="$sckt" \
    -O exit "$srvr"                   # terminating the master connection
clean || exit 4                       # removing the temporary directory

Tested on Kubuntu client connecting to Debian server. I'm not sure how robust it is. Treat it as a proof of concept. See man 1 ssh and man 5 ssh_config for details.