phdru.name / Software

SSH connection sharing

(Русская версия этого текста.)

OpenSSH4 on Unix allows connection sharing - utilizing one authenticated TCP connection for a number of SSH sessions. The advantage is that subsequent connections don't need to open a new TCP connections and don't need to pass the authentication phase, thus they initialize a session much faster. This is very useful for running a lot of short ssh sessions (scp, sftp, rsync, git, hg, svn over ssh).

Detailed docs are in man ssh_config; see options ControlMaster and ControlPath. See OpenSSH wikibook and search the web.

Add the following to your ~/.ssh/config:

ControlMaster auto
ControlPath ~/.ssh/.%r@%h:%p
ControlPersist 600

ControlMaster auto means the first client becomes the master, it opens TCP connection, authenticates and opens a unix socket named in ControlPath. Subsequent clients use the unix socket to connect to the server via the already established connection. In case the user tries to close the first (master) client it will wait until all sessions are finished; in case the user kills the master, it kills all its shared sessions.

ControlPersist prevents such killing by pre-forking a daemon that maintains the master connection for that number of seconds after the last client disconnected.

I use all 3 recommended macros, because I use ssh/scp/sftp/rsync/git/hg/svn to connect to a number of servers.

Drawbacks: the subsequent connections inherit some attributes of the master; agent forwarding, e.g. If ssh (or the OS, or even the entire computer) crashes one needs to remove unix sockets manually; to remedy this I changed ControlPath to ~/.ssh/controls/%r@%h:%p and added to my crontab:

@reboot rm -f .ssh/controls/*

This is the page https://phdru.name/Software/ssh_connection_sharing.html. It was generated on Tue, 13 Jul 2021 21:38:13 GMT from CheetahTemplate ssh_connection_sharing.tmpl. Some rights are reserved. Read more about technical aspects of the site.