SSH tunnel howto and hints attachment
mouse 2524 · person cloud · link
Last update
2019-08-21
2019
08-21
«relevant things about ssh tunnels»

A general tunnel command:

1
2
3
4
5
6
7
8
9
10
11
12
13
ssh myuser@mysrv
  -L   8080:localhost:80  # tunnel local_port:target:target_port
  -L *:8080:localhost:80  # tunnel open to everyone who can connect to this machine
  -R   3380:localhost:80  # reverse tunnel port_on_mysrv:target:target_port
  -R *:3322:localhost:22  # reverse tunnel open to everyone who can connect to mysrv
  -q # quiet mode
  -f # go to background
  -n # redirects stdin from /dev/null
  -N # do not execute a remote command
  -T # disable pseudo-terminal allocation
  -M -S /path/to/socket # enable master mode via a shared socket
  -o UserKnownHostsFile=/dev/null # do not update known_hosts file
  -o StrictHostKeyChecking=no     # do no check the empty known_hosts file

Note: to allow the creation of reverse tunnels opened to everyone (0.0.0.0) you have to set this option:

1
2
# server configuration: /etc/ssh/sshd_config
GatewayPorts clientspecified

Scriptable tunnels

You can look for process IDs via pgrep/pkill:

1
2
ssh -fnNT ... mysrv          # start
pkill -f -QUIT 'ssh.*mysrv'  # stop

or better use master mode to avoid both grepping and any timing issues:

1
2
3
ssh -fNM -S /path/to/socket ... mysrv  # start
ssh -S /path/to/socket -O check        # check
ssh -S /path/to/socket -O exit mysrv   # stop

Auto-closing tunnels

SSH runs the specified command and then exits only if no one is using the tunnel:

1
2
ssh -f myusr@mysrv sleep 10  # start auto-closing tunnel
vncviewer 127.0.0.1::25901   # use the tunnel

Keep alive your connection

Keep alive the connection for 60 seconds, 1440 times (= 24 hours):

1
2
3
4
# client configuration: /etc/ssh/ssh_config | ~/.ssh/config
Host *
  ServerAliveInterval 60
  ServerAliveCountMax 1440
1
2
3
# server configuration: /etc/ssh/sshd_config
ClientAliveInterval 60
ClientAliveCountMax 1440

Test connectivity

1
ssh -o BatchMode=yes -o ConnectTimeout=3 myusr@mysrv exit && echo ok || echo ko

List active tunnels and ports

1
sudo lsof -i -n | egrep sshd

Source: Stackexchange - master mode, Patrickmn - keep alive, Stackoverflow - test, Superuser - list active tunnels