Zendo

Speed up SSH Connections

OpenSSH has the ability to keep a persistent connection to a remote server active for reuse whenever you run ssh to the same user on the same server.

This persistent connection removes the overhead of establishing a TCP connection and authenticating.

I found this especially useful in my local development environments where I have commands that execute on a local container over SSH.

This should also work for Vagrant and Ansible.

1. Update ~/.ssh/config

# Keep persistent connection open.
# See https://unix.stackexchange.com/a/244755
Host *                                                                                                                                                                                                                                      
   ControlMaster auto                                                                                                                                                                                                                       
   ControlPath ~/.ssh/master-socket/%r@%h:%p                                                                                                                                                                                                                                                                                                                                                                                             
   ControlPersist 300s

Ensure the new socket directory exists

mkdir --mode=700 ~/.ssh/master-socket/

2. (Optional) Open a persistent SSH connection

You may run the following before making additional SSH connections to ensure the persisted connection exists, however this should happen on all consequent ssh connections anyway.

ssh -fMN user@host

3. Run your SSH command

Run your ssh commands as normal

ssh user@host ls

References

#ops