Reputation: 2115
I got an SSH tunnel done with Pexpect
module which I'm only allowed to read from. How can I check if the connection is still up and running e.g. if there was any network connection issue in the meantime? The other side of my tunnel sends messages randomly so there may be like one day without any data in the stream. I've checked pexpect.isalive()
function but it seems like it doesn't detect that the network connection is down.
Upvotes: 1
Views: 903
Reputation: 20797
I think you can use ssh
's ServerAliveInterval
and ServerAliveCountMax
options:
ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=3 user@host ...
If your ssh
server does not support these options you can still try TCPKeepAlive
:
ssh -o TCPKeepAlive=yes user@host ...
And then in your pexpect
script you only need to check pexpect.EOF
.
The following is from ssh_config
man page:
ServerAliveCountMax
Sets the number of server alive messages (see below) which may be
sent without ssh(1) receiving any messages back from the server.
If this threshold is reached while server alive messages are
being sent, ssh will disconnect from the server, terminating the
session. It is important to note that the use of server alive
messages is very different from TCPKeepAlive (below). The server
alive messages are sent through the encrypted channel and there-
fore will not be spoofable. The TCP keepalive option enabled by
TCPKeepAlive is spoofable. The server alive mechanism is valu-
able when the client or server depend on knowing when a connec-
tion has become inactive.
The default value is 3. This option applies to protocol
version 2 only.
ServerAliveInterval
Sets a timeout interval in seconds after which if no data has
been received from the server, ssh(1) will send a message through
the encrypted channel to request a response from the server. The
default is 0, indicating that these messages will not be sent to
the server. This option applies to protocol version 2 only.
TCPKeepAlive
Specifies whether the system should send TCP keepalive messages
to the other side. If they are sent, death of the connection or
crash of one of the machines will be properly noticed. However,
this means that connections will die if the route is down tempo-
rarily, and some people find it annoying.
The default is ``yes'' (to send TCP keepalive messages), and the
client will notice if the network goes down or the remote host
dies. This is important in scripts, and many users want it too.
Upvotes: 1