【问题标题】:Set SSH connection timeout设置 SSH 连接超时
【发布时间】:2012-05-01 12:39:39
【问题描述】:

我正在尝试减少 ssh 尝试打开与主机的连接的时间。例如,如果我输入ssh www.google.com,则提示返回需要很长时间。

我读到过使用ssh -o ConnectTimeout=10 www.google.com,但即使这样也需要很长时间。是否有一些我可以修改以减少阻塞时间的尝试?

【问题讨论】:

  • 来自 ssh docs:“使用它来指定连接到 SSH 服务器时使用的超时时间(以秒为单位),而不是使用默认的系统 TCP 超时时间。此值仅在目标关闭时使用或者真的无法访问,而不是当它拒绝连接时。”

标签: ssh timeout


【解决方案1】:

问题可能是 ssh 试图连接到 所有 www.google.com 解析到的不同 IP。例如在我的机器上:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

如果我使用特定的 IP 运行它,它会更快地返回。

编辑:我已经计时(使用time),结果是:

  • www.google.com - 5.086 秒
  • 173.94.43.16 - 1.054 秒

【讨论】:

  • 想象一下如果上面的连接真的通过了:)
【解决方案2】:

ConnectTimeout 选项允许您告诉 ssh 客户端在返回错误之前您愿意等待连接多长时间。通过将 ConnectTimeout 设置为 1,您实际上是在说“最多尝试 1 秒,如果尚未连接则失败”。

问题在于,当您按名称连接时,DNS 查找可能需要几秒钟的时间。通过 IP 地址连接要快得多,实际上可能在一秒钟或更短的时间内工作。 sinelaw 正在经历的是,每一次通过 DNS 名称连接的尝试都不会在一秒钟内发生。 ConnectTimeout 的默认设置遵循 linux 内核连接超时,通常很长。

【讨论】:

  • DNS 查找需要几秒钟是相当不寻常的。