Search code examples
ruby-on-railsrubysshnet-ssh

Net-ssh timeout for execution?


In my application I want to terminate the exec! command of my SSH connection after a specified amount of time.

I found the :timeout for the Net::SSH.start command but following the documentation this is only for the initial connection. Is there something equivalent for the exec command?

My first guess would be not using exec! as this will wait until the command is finished but using exec and surround the call with a loop that checks the execution status with every iteration and fails after the given amount of time.

Something like this, if I understood the documentation correctly:

server = NET::SSH.start(...)

server.exec("some command")

start_time = Time.now
terminate_calculation = false

trap("TIME") { terminate_calculation = ((Time.now - start_time) > 60) }
ssh.loop(0.1) { not terminate_calculation }

However this seems dirty to me. I expect something like server.exec("some command" { :timeout=>60}). Maybe there is some built in function for achieving this functionality?


Solution

  • I am not sure if this would actually work in a SSH context but Ruby itself has a timeout method:

    server = NET::SSH.start ...
    timeout 60 do
      server.exec! "some command"
    end
    

    This would raise Timeout::Error after 60 seconds. Check out the docs.