2012-04-19 170 views
29

我试图减少时间ssh试图打开一个连接到主机。例如,如果我输入ssh www.google.com,则需要很长时间才会出现提示。设置SSH连接超时

我读了关于使用ssh -o ConnectTimeout=10 www.google.com来代替,但即使这需要很长时间。我可以修改一些尝试以减少阻塞时间吗?

+5

from ssh docs:“使用此参数指定连接到SSH服务器时使用的超时时间(以秒为单位),而不是使用默认的系统TCP超时值。仅当目标服务器关闭或无法访问时才使用此值,当它拒绝连接。“ – Adi 2012-04-19 22:14:32

回答

44

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

# 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地址连接要快得多,实际上可能在一秒钟或更短的时间内工作。正弦波正在经历的是,每次尝试通过DNS名称进行连接都无法在一秒内发生。 ConnectTimeout的默认设置遵循Linux内核连接超时,通常很长。

+4

DNS查找花费几秒钟的时间是非常不寻常的。 – 2016-06-22 16:00:03