Search code examples
ruby-on-railsrubysshnet-ssh

Ruby Net:SSH Control Master?


I currently have a Ruby (Rails) application that needs to make a lot of short SSH connections. This works fine using the Ruby Net::SSH library, except that the app has to log in and negotiate keys every time I want to make a command, which is too slow.

Is there a way to enable Control Master with Ruby Net::SSH? In testing on the command line, this makes logins (after the first one) very fast, since the connection is already open (keys are negotiated etc.).

If there is no way to do this with Net::SSH, can anybody suggest an alternative library that could do it?

I imagine this must be a common requirement, so hopefully someone can help.

Thanks!


Solution

  • Why not just keeping the connection open ? The ssh calls are dummy as I don't know the api but it serves its purpose:

    def ssh_execute(user, command)
      Thread.current[:user_connections] ||= {}
    
      unless Thread.current[:user_connections][user.id]
        Thread.current[:user_connections][user.id] = Net::SSH.connect(...)
      end
    
      ssh = Thread.current[:user_connections][user.id]
      ssh.run_command(command)
    end
    

    You will get one ssh connection per thread or if your application is deployed with passenger each process will have one connection and will reuse it.

    Is it what you want ?