Snowball27
Snowball27

Reputation: 31

Paramiko: How to recontinue an ssh connection after disconnection (Error: Socket is closed)?

Is there a way to recontinue an ssh connection after the connection was interrupted? Paramiko seems to have a timeout when it doesn't get any response from the connected device. After disconnection, if I try to execute something over the ssh connection, I get the error "Socket is closed". I do know that there is an option for timeout in ssh.connect() but I already tried to set it to 99999 and None but that didn't work. Btw, the program continuously tries to send input over ssh.write(). If that doesn't work, it waits for 2 seconds and tries again.

Upvotes: 3

Views: 4571

Answers (1)

Callam Delaney
Callam Delaney

Reputation: 660

Try something like this, it will write to the ssh connection and will reconnect if the connection times out.

def writeOrReconnect(towrite)
    try:
        return ssh.write(towrite)
    except socket.error as e:
        #re-connect here
        return ssh.write(towrite)

To use it..

writeOrReconnect('sudo apt-get install ufw') #or whatever you put inside ssh.write()

Upvotes: 1

Related Questions