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.

DisplayMyName
  • 223
  • 3
  • 9
  • Is there a reason you cannot run `vncviewer` before `ssh` (e.g. in the background)? Maybe you need the tunnel to be established first. Did I guess right? – Kamil Maciorowski Oct 11 '18 at 19:56
  • Yes, exactly. For "vncviewer" I have a script that takes input from command line, like "./myserverssh vnc". If there's "vnc" keyword there, then I want ssh console and vnc to be launched. If my command is only "./myserverssh", then I want only ssh console to be launched. Obviously it could work if I launch vnc first, but in case there's no connection made, I would need to close vncviewer manually. It's not a big deal, but I would prefer to find out if there's a way to make it right. – DisplayMyName Oct 11 '18 at 20:07

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.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202