1

I'm using paramiko for SSH connection with server. exec_command always hangs forever if server becomes unavailable (for example unexpectedly turned off) and timeout doesn't actually work. I also tried set_keepalive, but it doesn't work either. As far as I understood from source codes keepalive is implemented for server. It just sends something to the server periodically to keep connection alive, but doesn't check for any read timeout on the client side.

Is there any way to handle unexpected connection drops? Maybe you can suggest something better then paramiko or the way I can fix it?

I also tried to set TCP level keep alive, but it doesn't help much.

sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 10)
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10)
sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 3)
incognito
  • 457
  • 5
  • 19

1 Answers1

0

If you want the timeout to work, you probably need to use

import socket
socket.settimeout(<timeoutinseconds>)

This should set the timeout so that paramiko will respect it. Then if the timeout is reached it should throw an exception you can handle

joeButler
  • 1,643
  • 1
  • 20
  • 41
  • connect method takes timeout and calls sock.settimeout(timeout). This function is called and timeout is set, however this doesn't help in case of unexpected power off. If you turn of (not shut down) your SSH server client will hang forever. – incognito Dec 23 '14 at 16:06
  • For linux ssh client you can use `-o TCPKeepAlive=yes -o ServerAliveInterval=5` and it works perfectly fine, but I can't find such an option for paramiko. – incognito Dec 23 '14 at 16:07
  • Are you using ssh with key auth? Do you really need to hold the connections open for a long time while they might be idle? – joeButler Dec 23 '14 at 16:15
  • I'd probably just re-connect each time or run a small test on the connection before the main command and catching exceptions. This thread looks to be related: http://stackoverflow.com/questions/20147902/how-to-know-if-a-paramiko-ssh-channel-is-disconnected – joeButler Dec 23 '14 at 16:17
  • The problem is that it never throws an exception. It hangs and `exec_command` never returns. – incognito Dec 23 '14 at 16:18