-2

I have a script which is using Paramiko to SSH into a server and is querying some files on the order of a few times a second. Occasionally it will crash with a TimeOut error message with seeming no obvious pattern in how long into the runtime this occurs. When I try to debug and look for potential lulls in activity that might be causing a timeout I find that the script seems to be sending and receiving messages at a pretty uniform rate right up until the moment the error occurs, and with no obvious anomalies in the messages that are being passed before the connection breaks. It seems to happen no matter what timeout argument I pass the initial connection too

Is there something obvious I'm missing here that might be causing this? Unsure what would be useful sample code to provide in this case but happy to edit with more details if needed. Thanks!!

EDIT:

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(-credentials-)

while True:
    stdin, stdout, stderr = client.exec_command(command)
    data = stdin.readlines()
    print(data)

Over-simplified example of the kind of loop that my code runs that seems to run into timeout errors without warning

addawaddawoo
  • 47
  • 1
  • 5
  • 1
    If you want help, you need to provide the code , what you made so far. We can't guess what can be issue. – Thyrus Nov 30 '21 at 09:11
  • Well my point was that it's kind of independent of what I'm doing - at some point the connection closes in the middle of a loop despite no lull in activity. I thought there might be some known reasons why conenctions prematurely close in Paramiko without needing some dummy code. But I have added an example of some code which runs fine for anywhere from 30seconds to 5 minutes and then loses connection abruptly – addawaddawoo Nov 30 '21 at 09:54
  • So did you check server log to find out why (if) it closes the connection? – Martin Prikryl Nov 30 '21 at 10:31

1 Answers1

0

You have to sent an empty packet to keep the connection alive. Add client.get_transport().set_keepalive(60) after connecting.

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(-credentials-)
# sends an empty packet to keep the connection alive for every 60 seconds 
client.get_transport().set_keepalive(60)

while True:
    stdin, stdout, stderr = client.exec_command(command)
    data = stdin.readlines()
    print(data)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992