Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse an ssh connection

Tags:

ssh

I'm creating a small script to update some remote servers (2+)
I am making multiple connects to each server; is there a way I can reuse the SSH connections so I don't have to open too many at once?

like image 636
onassar Avatar asked Dec 05 '13 20:12

onassar


People also ask

Can you have 2 SSH sessions?

Yes it is possible, it is the default behavior. You can rely on it if you are using an updated version of SSH and it is no longer set to Protocol 1.

What is SSH master mode?

SSH master mode allows you to create multiple SSH sessions by multiplexing the underlying TCP connection. The master socket creates the channel and additional connections to the channel are made through file sockets.


2 Answers

If you open the first connection with -M:

ssh -M $REMOTEHOST 

subsequent connections to $REMOTEHOST will "piggyback" on the connection established by the master ssh. Most noticeably, further authentication is not required. See man ssh_config under "ControlMaster" for more details. Use -S to specify the path to the shared socket; I'm not sure what the default is, because I configure connection sharing using the configuration file instead.

In my .ssh/config file, I have the following lines:

host *   ControlMaster auto   ControlPath ~/.ssh/ssh_mux_%h_%p_%r 

This way, I don't have to remember to use -M or -S; ssh figures out if a sharable connection already exists for the host/port/username combination and uses that if possible.

This option is available in OpenSSH since 2004.

like image 161
chepner Avatar answered Sep 21 '22 04:09

chepner


I prefer the method described at Puppet Labs https://puppetlabs.com/blog/speed-up-ssh-by-reusing-connections

Add these lines to ~/.ssh/config and run mkdir ~/.ssh/sockets

Host *     ControlMaster auto     ControlPath ~/.ssh/sockets/%r@%h-%p     ControlPersist 600 

Read the full blog post for more useful information about what these do and the idiosyncrasies of ssh when used like this. I highly recommend reading the blog or you may find things don't work as you expect.

like image 27
Jason Avatar answered Sep 21 '22 04:09

Jason