9

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.

2 Answers2

17

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.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Jakuje
  • 21,357
  • percent_expand: unknown key %C – Łukasz Lew Jul 26 '15 at 01:32
  • 1
    It looks like the %C substitution was added in openssh-6.7 so it doesn't work in all openssh versions. If it doesn't work, you can always use %r@%h-%p as proposed in the other answer. I will update mine accordingly. – Jakuje Jul 26 '15 at 07:59
3

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 somehost@example.com

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 :

n.st
  • 8,128
spuder
  • 18,053