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?
The default timeout interval is 0 minutes. Use this value, if you do not want the SSH session to expire. The minimum timeout interval is 2 minutes. The maximum interval is 9999 minutes.
Login to the client machine and open the /etc/ssh/ssh_config file to set the necessary parameter values to increase the SS connection timeout. ServerAliveInterval and ServerAliveCountMax parameters are set to increase the connection timeout. These parameters work similarly to the server-side configuration parameters.
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.
I don't think there's a native way to do it in net/ssh. See the code, there's no additional parameter for that option.
One way would be to handle timeouts in the command you call - see this answer on Unix & Linux SE.
I think your way is better, as you don't introduce external dependencies in the systems you connect to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With