SSH Tunneling – How to Maintain Open SSH Connection for Shell Scripts

sshssh-tunneling

Currently i invoke the following:

$ ssh me@host.com my_cmd

This is slow and not easy to automate safely.
I would like to establish ssh connection once and have some script that will forward my commands to host.com and print output.

Is that possible ?

Adding my machine to authorized_keys is not an option for me and it wouldn't solve slowness issue.

Best Answer

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.

Related Question