25.3 SSH tunneling

SSH authentication can be more advanced than indicated above, especially on systems that require dual authentication. Even simple password-protection can be tricky in scripts, since (by design) it is fairly difficult to get SSH to accept a password from anything other than the raw keyboard input (i.e. SSH doesn’t let you pass passwords as input or arguments, because this exposes your password as plain text).

A convenient and secure way to follow SSH security protocol, but prevent having to go through the full authentication process every time, is to use SSH tunnels (or “sockets”, which are effectively synonymous). Essentially, an SSH socket is a read- and write-protectected file that contains all of the information about an SSH connection.

To create an SSH tunnel, use a command like the following:

ssh -n -N -f -o ControlMaster=yes -S /path/to/socket/file <username>@<hostname>

If appropriate, this will prompt you for your password (if using password authentication), and then will drop you back to the command line (thanks to the -N flag, which runs SSH without executing a command, the -f flag, which pushes SSH into the background, and the -n flag, which prevents ssh from reading any input). It will also create the file /path/to/socket/file.

To use this socket with another command, use the -S /path/to/file flag, pointing to the same tunnel file you just created.

ssh -S /path/to/socket/file <hostname> <optional command>

This will let you access the server without any sort of authentication step. As before, if <optional command> is blank, you will be dropped into an interactive shell on the remote, or if it’s a command, that command will be executed and the output returned.

To close a socket, use the following:

ssh -S /path/to/socket/file <hostname> -O exit

This will delete the socket file and close the connection. Alternatively, a scorched earth approach to closing the SSH tunnel if you don’t remember where you put the socket file is something like the following:

pgrep ssh   # See which processes will be killed
pkill ssh   # Kill those processes

…which will kill all user processes called ssh.

To automatically create tunnels following a specific pattern, you can add the following to your ~/.ssh/config

Host <hostname goes here>
 ControlMaster auto
 ControlPath /tmp/%r@%h:%p

For more information, see man ssh.