Q. How do I reuse same ssh connection to speed up remote login procedure with OpenSSH client?
A. You can restricts or reuse connection for remote server using controlmaster directive. To enables the sharing of multiple sessions over a single network connection add controlmaster after host directive. When set to yes ssh client will listen for connections on a control socket specified using the ControlPath argument. These sessions will try to reuse the master instance’s network connection rather than initiating new ones, but will fall back to connecting normally if the control socket does not exist, or is not listening.
Open ~/.ssh/config file (ssh client configuration file). If you need system wide settings add to /etc/ssh/ssh_config file:
$ vi ~/.ssh/config
Append following code to reuse ssh connection for all hosts:
host * controlmaster auto controlpath /tmp/ssh-%r@%h:%p
- controlmaster auto: Set controlmaster to auto
- controlpath /tmp/ssh-%r@%h:%p: Specify the path to the control socket used for connection sharing. In the path, ‘%h will be substituted by the target host name, %p the port, and %r by the remote login username. It is recommended that any ControlPath used for opportunistic connection sharing include at least %h, %p, and %r. This ensures that shared connections are uniquely identified.
You can also match any host in the 192.168.0.[0-9] network range with following pattern:
Host 192.168.0.? controlmaster auto controlpath /tmp/ssh-%r@%h:%p
For any host in the “.co.in” set of domains, reuse the connection:
Host *.co.in controlmaster auto controlpath /tmp/ssh-%r@%h:%p
Save and close the file. Now connect as usual,
$ ssh email@example.com
Next, time you connect again it will use connection socket /firstname.lastname@example.org:22 to speed up things. You don’t have to input password or anything else. You need one connection to be active for the second to be accelerated. This also works with scp / sftp etc:
$ scp /path/to/file.txt email@example.com:/tmp
A note about X11, ssh-agent and port forwarding
Please note that X11 and ssh-agent forwarding is supported over these multiplexed connections, however the display and agent forwarded will be the one belonging to the master connection i.e. it is not possible to forward multiple displays or agents. However, you can create new session as follows for port forwarding:
$ ssh -M -S /tmp/3001.port.forwording -L 3001:localhost:3001 -N -f firstname.lastname@example.org
- man pages ssh and ssh_config