How can I maintain open ssh connection and use it from shell scripts?

The feature is called ControlMaster which does multiplexing over one existing channel. It causes ssh to do all of the key exchanges and logging in only once; thus, the later commands will go through much faster. You activate it using these three lines in your .ssh/config:

Host host.com
  ControlMaster auto
  ControlPath ~/.ssh/master-%C
  # for openssh < 6.7 you need to use this one:
  # ControlPath ~/.ssh/master-%r@%h-%p
  ControlPersist 5m

You can adjust it to your needs; one alternative is that you could open one master connection that stays open during your other commands; then you would not need ControlPersist.

There are many possibilities with this feature to tweak, but make sure you store your ControlPath socket in a safe place, not readable by other users, otherwise it could be misused.

More info can be found in the ssh_config(5) manual page.


If you have control of the machine to the point that you are automating tasks on it, then why is adding your key to authorized_keys not an option?

ssh-copy-id -i ~/.ssh/foo [email protected]

Then you don't have to enter a password every time you connect.

If the biggest problem is that connections take a long time to connect, you could reuse a single connection by adding control master to your ssh config. Leave that one connection running, an any subsequent connections will be nearly instantaneous.

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

https://puppetlabs.com/blog/speed-up-ssh-by-reusing-connections

In the long run, if you are automating tasks, you are proabably better off using an automation framework that handles establishing the connection for you, like :

  • mcollective
  • ansible
  • rundeck