gpt4 book ai didi

python - 如何使用 Pexpect 监控 SSH 隧道的运行状况?

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:06 26 4
gpt4 key购买 nike

我使用 Pexpect 模块完成了一个 SSH 隧道,我只允许从中读取。我如何检查连接是否仍在运行,例如在此期间是否有任何网络连接问题?我隧道的另一边随机发送消息,因此可能有一天流中没有任何数据。我检查了 pexpect.isalive() 函数,但它似乎没有检测到网络连接已关闭。

最佳答案

我认为您可以使用sshServerAliveIntervalServerAliveCountMax选项:

ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=3 user@host ...

如果您的 ssh 服务器不支持这些选项,您仍然可以尝试 TCPKeepAlive:

ssh -o TCPKeepAlive=yes user@host ...

然后在您的 pexpect 脚本中,您只需检查 pexpect.EOF

<小时/>

以下内容来自 ssh_config 手册页:

 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.

关于python - 如何使用 Pexpect 监控 SSH 隧道的运行状况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41473000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com